danielad danielad -3 years ago 93
Node.js Question

getting async nodejs value from each callback calls

var async = require('async');

var square = function (id, callback) {
return callback(userObject);

async.eachSeries(findBusinessResult, function (businessObject, callback) {
//console.log("results from square");
var result = square(businessObject["id"] , function(result){
callback(); // Alternatively: callback(new Error());
}, function (err,results) {
if (err) { throw err; }
console.log('Well done :-)!');

Why does the result always become undefined: any help please.

Answer Source

I hope this will be a game changer solution for most ppl. This is making ASYC java callback into somthing which look like sync with effiecent callback handling. Its my three days of challange. Callbacks are indeed a a major challage in javacript and here is how to solve issue using promises .

install bluebird 
npm install bluebird --save

//inyour code

var Promise = require('bluebird'); //yeah awsome bird indeed :)

function extendBusinessObjectPromise(id,element) {
    return new Promise(function(resolve, reject) {
        Business.prototype.getBusinessUser( id ,function(userObject){
         var extend = require('util')._extend;
         mergedJson = userObject;
         elements = element;
         global.businesssWithUsers.push(elements); //sahred object


//NOW how do you i call the promise result inside a foreach loop and get its value returned as callback result. seem crazy idea :(

Person.prototype.getPersons = function(filter , callback) {
  //this my own Bill count since i have one using one user account
  global.businesssWithUsers = [];

models.PersonModel.findAll(filter_combined).then(function (findBusinessResult) {
  global.businesssWithUsers = []
  var extend = require('util')._extend;
  var mergedJsonArray =  [];

  if (findBusinessResult==null) {
    return callback(false,"no result found");

   var promiseBusinessResult = null; //promise reslover :)

   var findBusinessResult =JSON.parse(JSON.stringify(findBusinessResult));

    findBusinessResult.forEach(function(eachElement) {
      var id = element["userId"];
      promiseBusinessResult = extendBusinessObjectPromise(id,element);

       callback(true,result); //pass the result to main function

    }).catch(function (err) {

Success at last. Cheers! Daniel Adenew

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download