javascriptnode.jsasynchronousasana

Waiting for multiple async calls using async.each


I need to wait for few async calls to complete before resuming execution. I tried the following code using async.

asana.getUsers(null, function(error, resp){
    async.each(resp.data, function(user, cb) {
        console.log("Get info for user : ", user.id);
        asana.getUser(user.id, null, function(error, userResp){
            console.log("user response: ", userResp.data.id);
            userEmailList.push({
                id : userResp.data.id,
                name: userResp.data.name,
                email : userResp.data.email
            });
           cb(null);
        });
        //cb(null); Should the call be here??
    }, function(err){
        console.log("getUsers is done now");
    });
});

The log that i get is:

Get info for user :  xxxxxxxxxxxx
Get info for user :  yyyyyyyyyyyy
Get info for user :  zzzzzzzzzzzz
Get info for user :  aaaaaaaaaaaa
user response:  yyyyyyyyyyyy

/Code/javaScript/NodeWorkspace/asana-api/mail.js:23
            console.log("user response: ", userResp.data.id);
                                                   ^
TypeError: Cannot read property 'data' of null
    at /Code/javaScript/NodeWorkspace/asana-api/mail.js:23:43
    at Request._callback (/Code/javaScript/NodeWorkspace/asana-api/lib/asana.js:77:13)
    at Request.self.callback (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:119:22)
    at Request. (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:525:16)
    at Request.EventEmitter.emit (events.js:95:17)
    at IncomingMessage. (/Code/javaScript/NodeWorkspace/asana-api/node_modules/request/main.js:484:14)
    at IncomingMessage.EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:883:14
    at process._tickCallback (node.js:415:13)

I understand the first logs, but why is the console.log("user response: ", userResp.data.id); line getting called with userResp as null.

I hope its not some silly mistake. Thanks in advance.

P.S: Basically i need to get Asana users and then get info of each user and store in a var userEmailList.


Solution

  • The issue was that userEmailList was undefined.