node.jsasynchronousforEach两个数组
我有一个问题与asynchronous和两个数组。
我有两个数组
var arrayOne = new Array(); var arrayTwo = new Array();
我目前正在试图找出如何做一个瀑布内的以下asynchronous样式:
... // some code function (arrayOne, arrayTwo, callback) { // do stuff for(var i = 0; arrayOne.length > i; i++) { // do more stuff callback(e, arrayOne[i], arrayTwo[i]); } }, function (valueOne, valueTwo, callback) { ... // more code
我尝试使用async.foreach,但它只适用于一个数组:/
ERGO:
... // some code function (arrayOne, arrayTwo, callback) { // do stuff forEach(arrayOne, function(valueOne, callback) { // do more stuff }, function(e){ // do more stuff callback(e, valueOne, /* valueTwo???? */); }); }, function (valueOne, valueTwo, callback) { ... // more code
使用async.times
循环使用最短数组的长度:
function task( a, b, next ) { setTimeout( function() { next( null, a + b ); }, 1000 ); } function work( a, b, done ) { async.times( Math.min( a.length, b.length ), function( i, next ) { task( a[i], b[i], next ); }, done ); } var a = [1, 1, 1, 1]; var b = [1, 1, 1]; work( a, b, function( err, result ) { console.log( 'result:', result ); }); console.log( 'continuing...' );
// 2个数组的async.map应该是这样的:
function map(a, b, func, cb) { var results = []; var length = Math.min(a.length, b.length); var countdown = length; // count to 0 for(var i=0; i < length; i++) { func(a[i], b[i], function (err, result) { results.push(result); countdown--; if(countdown === 0) { cb(null, results) // cb is call on last result } }) } }
//testing
var a = [1,1,1]; var b = [2,2,2]; function sum(a, b, cb) { // simulate async with timeout setTimeout(function () { cb(null, a + b); }, 1000); } map(a, b, sum, function (err, results) { console.log(results); })
输出继电器:
[ 3, 3, 3 ]
我认为你正在推翻它:
function (arrayOne, arrayTwo, callback) { forEach(arrayOne, callback, function(){ forEach(arrayTwo, callback); }); };