2

Code Snippets:

var async = require("async");

async.map([
    "a",
    "b",
    "c"
], function(thing, callback) {
  console.log(thing + "-something");
  callback();
},
function(err, results){
    if (err) return console.error(err);
    console.log(results);
});

My current results:

a-something
b-something
c-something
[ undefined, undefined, undefined ]

My desired results:

[ a-something, b-something, c-something ]

Could you guys tell me what I am getting wrong? How do I have access to the results object in the callback?

1 Answer 1

4

You need to pass your result into callback() as the second parameter (the first parameter should be the error if there is any):

var async = require("async");

async.map([
    "a",
    "b",
    "c"
], function(thing, callback) {
  var returnValue = thing + "-something";
  console.log(returnValue);
  callback(null, returnValue);
},
function(err, results){
    if (err) return console.error(err);
    console.log(results);
});
Sign up to request clarification or add additional context in comments.

2 Comments

This works! Thanks Oleg. I wanted to bother you with one more question, I am new to javascript and node and I find the documentation to be diffcult to read. How come callback() also works, in the absense of any argument being passed in. Could you refer me to the documentation that shows callback(null, returnValue)
@SidneySidaZhang: This is the section of the docs you should look at: github.com/caolan/async#maparr-iterator-callback. The reason callback() also works is because JavaScript isn't strict with the number of parameters passed to a function (any parameters not passed are treated as undefined). The async library follows suit and chooses to be relaxed about requiring the parameters so if you don't pass anything in, it assumes theres no error, and like you saw, passes undefined to the last callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.