使用 Async.Parallel Node.js 同时搜索多个数组

Search Multiple Arrays simultaneously using Async.Parallel Node.js

我正在尝试搜索可变数量的数组,当在其中任何一个中找到给定值时返回 true。

我想知道我应该如何解决这个问题,因为数组可能非常大。 (我使用 Array.prototype.forEach 成功了,但是 'blocking' 我想使用异步版本)

下面是我当前尝试的抽象。

 var desired_value = 'example'   
 (function(callback) {

     async.each(arry1, function(somevalue, callback) {
       if(somevalue === desired_value) return callback(null, true);
     });

     async.each(arry2, function(somevalue, callback) {
      if(somevalue === desired_value) return callback(null, true);
     });

     async.each(arry3, function(somevalue, callback) {
      if(somevalue === desired_value) return callback(null, true);
     });

 })(function(err, result) {
     return (!result || err) doThis() : doThat();
 });

阅读关于异步并行的说明:

Note: parallel is about kicking-off I/O tasks in parallel, not about parallel execution of code. If your tasks do not use any timers or perform any I/O, they will actually be executed in series. Any synchronous setup sections for each task will happen one after the other. JavaScript remains single-threaded.

https://github.com/caolan/async#paralleltasks-callback

编辑:至于错误,parallel 需要执行一组函数。但是,您使用的结果 async.each 没有 return 任何东西。

编辑:让其他人了解如何以非阻塞方式执行非 IO 代码:

function nonblockEach(arr, fn, iterations) {
  if (iterations == undefined) iterations = 1000;
  var count = 0;
  return function(callback) {
    var index = 0;
    function exec() {
      while (count < iterations && index < arr.length) {
        var element = arr[index];
        fn(element, index, arr);
        index++;
        count++;
      }
      if (index < arr.length) process.nextTick(exec);
      else callback();
    }
    process.nextTick(exec);
  }
}
var desired_value = 'example'   
var found = false;
async.parallel([
  nonblockEach(arry1, function(some_value) {
    found = found || (some_value === desired_value);
  }),
  nonblockEach(arry2, function(some_value) {
    found = found || (some_value === desired_value);
  }),
  nonblockEach(arry3, function(some_value) {
    found = found || (some_value === desired_value);
  })
], function(err) {
  return (found) ? something() : anotherThing();
});

未测试,但它给了你想法。