Node.jsasynchronous循环function

我是Node.js的新手,很想知道这是否是正确的方法:

我正在使用狼疮来处理for循环,我正在查询Twitter API,然后我试图得到返回的JSON中最大的ID,为此我使用lodash 。 一旦我有了这个值,我想再次运行循环,但这次是传递给函数的值。 我使用async.js通过返回的JSON进行循环

lupus(0, loopLength, function(n) { var maxId; T.get('favorites/list', {count: 200, max_id: maxId}, function(err, data, response) { if (err) { throw (err); } maxId = _.max(_.pluck(data, "id")); async.each(data, function(file, callback) { console.log(file) }, function(err){ if( err ) { console.log('A file failed to process: '+ err); }); }) }, function() { console.log('All done!'); }); }) 

似乎maxId永远不会被设置,所以.each循环永远不会获得下一组JSON。 我的问题是我正确做这个,我怎么从.each函数得到maxId的值。

问题是你有两个asynchronous的事情(狼疮“循环”和T.get调用),基本上没有他们之间的协调。

因为T.get将是asynchronous的,所以我不会在这里使用红斑狼疮(呃!):

 var index = 0; var maxId; next(); function next() { T.get('favorites/list', {count: 200, max_id: maxId}, function(err, data, response) { if (err) { throw (err); } maxId = _.max(_.pluck(data, "id")); async.each(data, function(file, callback) { console.log(file) }, function(err){ if( err ) { console.log('A file failed to process: '+ err); }); if (++index < loopLength) { next(); } else { console.log('All done!'); } }); } 

在代码中有几个不相关的东西看起来不对:

  1. 在第一次调用maxId时,如果您从未maxId赋值,则使用T.get 。 好像你想要某种初始值。

  2. 你从T.getcallback中抛出一个错误。 T.get的文档是否告诉你它会做一些有用的错误? 如果没有,你可能想要做别的事情。 例如,扔在那里将不会停止在您的原始代码循环(它将与上面的代码)。