2015-11-06 43 views
0

我试图搜索可变数量的数组,当在其中任何一个数组中找到给定值时返回true。使用Async.Parallel Node.js同时搜索多个阵列

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

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

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(); 
}); 
+0

我删除了对async.parallel的调用,因为我的代码没有执行任何I/O – neverknown

回答

0

阅读有关异步并行注:

注:平行约为踢关闭I /并行O任务,不是 代码的并行执行。如果你的任务不使用任何定时器或执行任何I/O,它们将实际上被串行执行。任何 每个任务的同步设置部分将在 之后发生。 JavaScript仍然是单线程的。

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

编辑:至于错误,parallel需要的函数来执行的阵列。但是,您正在使用结果async.each,该结果不会返回任何内容。

编辑:为了让别人如何在非阻塞的方式执行非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(); 
}); 

没有测试,但它给你的想法。

+0

我明白了。我现在就拉这个。感谢您的快速回复! – neverknown

+0

把东西放在纯代码async – TbWill4321

+0

谢谢!这工作完美。 – neverknown