getting async nodejs value from each callback calls

70 views Asked by At
var async = require('async');

var square = function (id, callback) {
  Business.prototype.getBusinessUser(id,function(userObject){
    return callback(userObject);
  });
 };


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

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

2

There are 2 answers

0
Develop4Life On BEST ANSWER

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][1] 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;
         extend({},elements);
         extend(elements,mergedJson);
         global.businesssWithUsers.push(elements); //sahred object
        resolve(global.businesssWithUsers)
        })
})

}

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

    promiseBusinessResult.done(function(result){
       callback(true,result); //pass the result to main function
     });

    }).catch(function (err) {
      log.error(err["errors"][0]["message"])
      callback(false,err["errors"][0]["message"])
      return
    })
}

Success at last. Cheers!

0
Endless On

async is reserved word in ES7 and might give you problem later, when it's implemented.
What you might want to consider is actually using async/await togheter with babel.
Some browser is starting to implement it already

var square = id => 
    new Promise(rs => 
        Business.prototype.getBusinessUser(id, rs)
    )

async search() {
    for (let businessObject of findBusinessResult) {
        let result = await square(businessObject.id)
        console.log(result)
    }
}