1

I'm using Async to call a function in which it asynchronously calls db and fetches some values then it returns that value to the callback of the async.series. But then how can I pass the value as a return value of the outer function?

Please refer to the comments in the code below for more info.

getUserObjFromDb = function(username, cb) {
    var user = {};
    async.series([
            function(callback){
                var userObj = callDb(username);
                callback( null, userObj );
            }
        ],
        function(err, results){
            user = results[0];
            cb(user);
        });
}

var theUser = getUserObjFromDb(username, function(user){
  return user;
}); // theUser is undefined because the outer function getUserObjFromDb did not return anything even though its callback returned, it was only the callback of the async.series which returned. 

How can I get the value of user inside passed to theUser ?

I could be doing all this completely wrong and there could be a much simpler approach, so any help would be appreciated. Thank you.

Amir Mog
  • 321
  • 1
  • 4
  • 17

2 Answers2

1

Honestly, I'm not entirly clear on the question. I'm guessing you are expecting the getUserObjFromDb to return the value that the callback returns. If so, Try this:

getUserObjFromDb = function(username, cb) {
        var user = {};
           return async.series([
                    function(callback){
                        var userObj = callDb(username);
                        return callback( null, userObj );
                    }
                ],
                function(err, results){
                    user = results[0];
                    cb(user);
                });
        }
Aragorn
  • 5,021
  • 5
  • 26
  • 37
  • This is perfect. I think this should just work. That said, since we are returning the result of the async, could I not have a callback for the getUserObjFromDb and instead return the user directly from inside the async's callback? would that work? getUserObjFromDb = function(username) { var user = {}; return async.series([ function(callback){ var userObj = callDb(username); return callback( null, userObj ); } ], function(err, results){ user = results[0]; return user; }); } – Amir Mog Nov 06 '15 at 18:54
  • You can only return one value. Either return callback( null, userObj ); or return results[0]; – Aragorn Nov 06 '15 at 19:12
  • There's no apparent benefit in assigning `var user = {};` or `user = results[0];`. Would `cb(results[0]);` not have the desired effect? – Roamer-1888 Nov 06 '15 at 21:17
1

You are mixing up synchronous and asynchronous models here. The function call getUserObjFromDb is executing right away, and since the async call hasn't completed you can't return it's value from that function.

That is why a callback is necessary. Any code that requires the value for the user needs to be triggered by your callback.

Chuck Skoda
  • 103
  • 9