Nodejs回调异步

Nodejs回调异步

问题描述:

users = []; 
    .on('result', function(user) { 
      async.waterfall([ 
       function(cb) { 
        get_comm(user.post_id, function(comms) { 

         user.comm = comms; 
         users.push(user); 
         cb(users); 
        }) 
       }, 
      ], function(users, cb) { 

       console.log(users); // it prints out 
      }); 

     }) 
     .on('end', function() { 
      if (connectionsArray.length) { 
       pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL); 
       updateSockets({ 
        users: users // empty []; !! 

       }); 

      } 
     }); 

所以我想在结果循环完成后打印出所有的数据,但数组在结果循环中已满并空出它。Nodejs回调异步

+0

var get_comm = function(post_id,cb){varcomments = connection.query(..); comments.on('end',function(){ cb(comms);})} users = []; var query = connection.query(...); 。对( '结果',功能(用户){ async.waterfall([ 函数(CB){get_comm(user.post_id,函数(通讯){ user.comm =通讯科; users.push(用户); CB(用户); }) }, ],功能(用户,CB){ 的console.log(用户); //它打印出 }); }) 。对( 'end',函数()if(connectionsArray.length){pollingTimer = setTimeout(pollingLoop,POLLING_INTERVAL); updateSockets({ rs:users // empty []; ! }); } }); – 2014-11-20 22:38:39

+0

这里是完整的代码检查@ jfriend00 – 2014-11-20 23:18:11

我假设on方法来自EventEmitter的实例。如果是这样,回传到on的回调不具备异步功能。

你的代码正在做他们的异步。