Node.js 等待节点异步操作
我想使用索引大约20个目录,每个目录中大约有10000个文件。我预计操作需要几个小时,所有数据都无法放入内存,我希望一次将加法批处理成10或20个 基本代码如下所示,创建搜索索引并在准备就绪时执行回调函数,其中包含实例“si”:Node.js 等待节点异步操作,node.js,asynchronous,synchronization,Node.js,Asynchronous,Synchronization,我想使用索引大约20个目录,每个目录中大约有10000个文件。我预计操作需要几个小时,所有数据都无法放入内存,我希望一次将加法批处理成10或20个 基本代码如下所示,创建搜索索引并在准备就绪时执行回调函数,其中包含实例“si”: searchIndex(siOptions, (sierr, si) => { // here I list the files and want to do batch adds: while (true) { var batch = getBa
searchIndex(siOptions, (sierr, si) => {
// here I list the files and want to do batch adds:
while (true) {
var batch = getBatch();
if (!batch) break;
si.add(batch, options, (err) => {
console.timeEnd('batch');
});
}
});
所以我的基本想法是循环目录,写出我正在处理那个目录,列出文件,然后一次处理20个文件:
_.each(subDirs, dir => {
// list files
// pull 20 files at a time
// do add above
});
所以我知道我该怎么做,但该死的,它看起来很丑。能够同步运行是很理想的,但是有一些实用程序库我可以使用吗?我的想法是创建一个函数来处理一个目录,并一次遍历一个目录,然后在回调中递增计数器并调用它自己
var dirIndex = 0;
var doDir = function(cbDir) {
if (dirIndex >= dirs.length) cbDir(); // done
var batches = _.chunk(fs.readdirSync(dirs[dirIndex]), 20);
var batchIndex = 0;
var doBatch = function(cbBatch) {
if (batchIndex >= batches.length) {
cbBatch();
return;
}
console.time('batch');
si.add(batch[batchIndex++], options, (err) => {
doBatch(cbBatch); // process next batch, have it call our callback
});
};
doBatch(() => doDir(cbDir)); // final callback will do next dir
}
看起来我可能会对可变范围等问题敞开心扉。有更好的办法吗?我一直假设搜索索引不会出现问题,因为函数
searchIndex(siOptions,(sierr,si)=>{
在所有操作完成之前就返回了…如果要同步运行代码,可以尝试setTimeout()如果你想同步运行你的代码首先想到的两件事是要么或承诺。async
会修改你代码的一部分,但要保持代码的整洁、异步。承诺现在是首选,我已经看到它们被用来“同步”代码,所以可能更适合。首先想到的两件事是要么或承诺。async
会修改代码的一大部分,但要保持代码的整洁、异步。承诺现在更受欢迎,我看到它们用于“同步”代码,所以可能更适合。