等待节点异步操作

时间:2016-08-19 08:53:10

标签: node.js asynchronous synchronization

我想使用search-index索引大约20个目录,每个目录中包含大约10,000个文件。我希望这个操作需要几个小时,而且所有的数据都不适合内存,而且我想将这些数据分批批量添加到十或二十个。

基本代码如下所示,创建搜索索引并在准备就绪时执行回调函数,其中包含实例'si':

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');
    });
  }
});

所以我的基本想法是遍历目录,写出我正在处理该目录,列出文件,并一次批量处理文件:

_.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) => {已经返回...

1 个答案:

答案 0 :(得分:0)

如果要同步运行代码,可以尝试使用setTimeout()

相关问题