Skip to content Skip to sidebar Skip to footer

Optional Callback Not Being Called In The Node.js Async Module's Foreachof Method

I'm using the async module's forEachOf method to print the end result after iterating through an object. Here is a shortened version of what I'm doing: var async = require('async')

Solution 1:

Your statement:

if (err) {
    return callback(err);
}

is not valid for asynchronous programming. Instead, you should do:

if(err) callback(err);

This is why you aren't getting anything returned. I rewrote your code with async concepts applied:

varasync = require('async'),
var cheerio = require('cheerio'),
var request = require('request');

var returnArray = [];
async.forEachOf(myObj, function (value, key, next) {
    var anotherObj = {};

    anotherObj.type = "val1";

    request(someurl, function(err, res, body) {
        if (err) next(err);

        var $ = cheerio.load(body);

        anotherObj.name = "val2";

        var miniObj = {};
        async.each($('#some-element', "#an-id"), function (value, next) {
          var val = value.value;
          miniObj[size] = val;
        });

        anotherObj.miniObj = miniObj;

        returnArray.push(anotherObj);

        next();
    });
}, function (err) {
    if (err) console.error(err.message);

    console.log(returnArray);
    callback(returnArray);

});

Notice that you have two different named callbacks. The outer function callback is called callback. The inner function callback is called next.

Post a Comment for "Optional Callback Not Being Called In The Node.js Async Module's Foreachof Method"