我是 Node.js 新手,正在努力了解这是否是执行以下操作的正确方法:
我正在使用lupus为了处理 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 的值。
最佳答案
问题在于,您有两个异步事件正在发生(狼疮“循环”和 T.get
调用),并且它们之间基本上没有协调。
因为 T.get
是异步的,所以我根本不会在这里使用 lupus(呃!):
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!');
}
});
}
<小时/>
代码中有一些不相关的内容看起来不正确:
在第一次调用
T.get
时,您在使用maxId
时从未为其赋值。看起来你想要某种初始值。您从
T.get
回调中抛出错误。T.get
的文档是否告诉您它将针对该错误执行一些有用的操作?如果没有,您可能想做其他事情。例如,抛出该异常不会停止原始代码中的循环(上面的代码会)。
关于javascript - Node.js 异步循环函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29716895/