1

How to return the final result/callback to the calling function? All examples in the documentation only show console.log() options.

The following code is just for example purposes.

function foo(input) {
    async.parallel([
        function(callback) {
            callback(null, input.one);
        },
        function(callback) {
            callback(null, input.two);
        }
    ],
    function(err, results) {
        // What to do here? all examples include console.log()
        // I want to return the result ([1, 2]) to the calling function!
    });
}

var data = {"one": 1, "two": 2};
var bar = foo(data);

console.log(bar); // Will return [1, 2]

Edit: This question was marked as duplicate. The other post did not explain how this was done to someone with marginal experience with javascript and callbacks.

1 Answers1

2

If your function contains async code so it becomes an async function. You need to include a callback :

    function foo(input, cb) {

       async.parallel([
          function(callback) {
              callback(null, input.one);
          },
          function(callback) {
            callback(null, input.two);
          }
      ],
      function(err, results) {
       return cb(results);
      });
   }

And modify your call :

var data = {"one": 1, "two": 2};
foo(data, function(bar){
  console.log(bar);

});
Daphoque
  • 4,421
  • 1
  • 20
  • 31