2c2c 2c2c - 5 months ago 23
Node.js Question

async code in forEach loop nodejs

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


  • takes an
    offer
    object (dependency)

  • reads from the offer object an
    items
    array through a callback (dependency)

  • iterates each item

  • takes some values from the
    offer
    and
    item
    objects

  • reads from db some statistical data to determine the item's value

  • writes above two line's fields to an array

  • pushes the array to an array of arrays

  • uses this array to insert rows into db



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.

Answer

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