2c2c
2c2c

Reputation: 4864

async code in forEach loop nodejs

I have been trying to write some code that writes rows to my database. it:

function WriteToDB(object) {
  object.getItems(function (err, items) {
  var rowlist = [];
  items.forEach(function (item) {
    var field1 = offer.name;
    var field2 = item.name;
    var field3 = getItemValue(item.name); //async db call
    var row = [field1, field2, field3];
    rowlist.push(row);
  });

  write(valuelist);
}

i know this wont work, but i can't seem to grok nodejs enough to figure out how to solve this simple to be done task in other languages. I messed with learning async.waterfall, but got confused because there's a synchronous foreach loop mixed in the chain of otherwise pretty asynchronous stuff.

Upvotes: 0

Views: 208

Answers (2)

Oscar Reyes
Oscar Reyes

Reputation: 4342

You can use a library i just created called utils-pkg which has a function called .each() that iterates each element from an object or array. It is not synchronous but with the callback you can continue to next iteration when asked

Also the function has another callback parameter which is executed once all the iterations are done

Check the package here

var utils = require("utils-pkg");

function WriteToDB(object) {
    object.getItems(function (err, items) {
        var rowlist = [];

        utils.each(items, function(index, value, next){
            var field1 = offer.name;
            var field2 = value.name;
            var field3 = getItemValue(value.name); //async db call
            var row = [field1, field2, field3];

            rowlist.push(row);
            next();  // call this once you are done with this iteration
        }, function(){
            // This is called when all iterations are done
            write(valuelist);
        });
    });
}

Upvotes: 0

Quanlong
Quanlong

Reputation: 25476

You can use async module, like:

var async = require('async');

function WriteToDB(object) {

    object.getItems(function (err, items) {
        var rowlist = [];

        async.each(items, function (item, cb) {
            var field1 = offer.name;
            var field2 = item.name;
            getItemValue(item.name, function (value) {
                var field3 = value;
                var row = [field1, field2, field3];
                rowlist.push(row);
                cb();
            }); //async db call

        }, function () {

            // All async read are completed here
            write(rowlist);
        });
    });
};

Upvotes: 1

Related Questions