使用async.each等待多个异步调用

时间:2013-12-19 17:13:09

标签: javascript node.js asynchronous asana

我需要等待几个异步调用才能完成,然后才能恢复执行。我使用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");
    });
});

我得到的日志是:

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)

我了解第一个日志,但为什么console.log("user response: ", userResp.data.id);行被userResp调用为null

我希望它不是一些愚蠢的错误。提前谢谢。

P.S:基本上我需要获得Asana用户,然后获取每个用户的信息并存储在var userEmailList中。

1 个答案:

答案 0 :(得分:0)

userEmailList未定义! 谢谢@damphat。