node.js async forEach两个数组

时间:2013-12-12 23:28:25

标签: node.js

我遇到了异步和两个数组的问题。

我有两个数组

var arrayOne = new Array();
var arrayTwo = new Array();

我目前正试图弄清楚如何在瀑布中执行以下异步样式:

... // 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但它只适用于一个数组:/

麦角:

... // 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

3 个答案:

答案 0 :(得分:3)

使用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...' );

答案 1 :(得分:2)

// 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
            }
        })
    }
}

// test

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 ]

答案 2 :(得分:0)

我认为你是在思考它:

function (arrayOne, arrayTwo, callback) {
    forEach(arrayOne, callback, function(){
       forEach(arrayTwo, callback);
    });
};