【问题标题】:Wait for node asynchronous operation等待节点异步操作
【发布时间】:2016-12-26 08:52:01
【问题描述】:

我想使用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');
    });
  }
});

所以我的基本想法是遍历目录,写出我正在处理该目录,列出文件,并一次处理 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
}

似乎我可能会对变量范围等问题敞开心扉。有没有更好的办法?我一直假设 search-index 不会有问题,因为函数 searchIndex(siOptions, (sierr, si) => { 在所有操作完成之前就返回了......

【问题讨论】:

  • 首先想到的两个是async 或Promises。 async 会修改你的大部分代码,但要保持它漂亮、干净和异步。如今,Promise 是首选,我已经看到它们用于“同步”代码,因此可能更合适。

标签: node.js asynchronous synchronization


【解决方案1】:

如果你想同步运行你的代码,你可以试试 setTimeout()

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    相关资源
    最近更新 更多