Trung Tran
Trung Tran

Reputation: 13721

Node.js async array iteration

I am trying to synchronously iterate over an array using async.each:

async.each(supplier_array, function(supplier) {
    console.log('looking at : ' + supplier);
    knex(host_name + '.order_item').where({
        supplier: supplier,
        order_id: order_id
    }).then(function(data) {
        console.log(data);
        knex(host_name + '.distributor').select()
        .then(function(data) {
            console.log(data);
        }).catch(function(error) {
            console.log('error: ' + error);
        });
    }).catch(function(error) {
        console.log('error: ' + error);
    });
});

My supplier_array has 3 elements. So what SHOULD happen is the app should (synchronously):

For supplier 1 / first arr / first array element:

For supplier 2 / second array element:

For supplier 3 / third array element:

HOWEVER, it acts asynchronously:

Can someone help me achieve the desired effect of running through the steps inside of async synchronously?

Thanks in advance!

Upvotes: 2

Views: 1918

Answers (1)

Donghua Li
Donghua Li

Reputation: 451

You should use async.eachSeries if you want to iterate them in serial order. Try something like this:

async.eachSeries(supplier_array, function(supplier, callback) {
    console.log('looking at : ' + supplier);
    knex(host_name + '.order_item').where({
        supplier: supplier,
        order_id: order_id
    }).then(function(data) {
        console.log(data);
        knex(host_name + '.distributor').select()
        .then(function(data) {
            console.log(data);
            callback(); // Advance to next iteration here
        }).catch(function(error) {
            console.log('error: ' + error);
            callback(error); // Also callback when error occurs
        });
    }).catch(function(error) {
        console.log('error: ' + error);
        callback(error); // Also callback when error occurs
    });
});

Upvotes: 3

Related Questions