1

I have an issue with async and two arrays.

I have two arrays

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

I am currently trying to figure out how to do the following async style inside a waterfall:

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

I tried using the async.foreach but it only applys to one array :/

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

3 Answers 3

3

Loop over the length of the shortest array using 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...' );
Sign up to request clarification or add additional context in comments.

Comments

2

// async.map for 2 arrays should be like this:

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

ouput:

[ 3, 3, 3 ]

Comments

0

I think you're overthinking it:

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

1 Comment

In the example, callback is called with an element from each array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.