我有一个async.whilst
循环,它循环遍历hashtag
每个循环中调用的字符串数组。
在for循环中,searchTwitter()
功能被触发。我需要for循环暂停,直到从searchTwitter()
函数返回回调为止,然后有2秒的暂停,然后for循环继续到hashtag
数组中的下一个字符串传递给searchTwitter()
。
在for循环完成之后,async.whilst循环中会出现超时,持续10秒,然后while循环再次重新加载for循环。
我下面的代码searchTwitter()
立即触发所有功能,而无需等待回调或setTimeout(callback,2000)
:
async.whilst(
function () { return 0 == 0 },
function (callback) {
for (var i = 0; i < hashtag.length; i++) {
searchTwitter(hashtag[i]);
setTimeout(callback, 2000);
}
setTimeout(callback, 10000);
},
function (err) {
}
);
function searchTwitter(tag, callback){
T.get('search/tweets', { q: '#fun', count: 100 }, function(err, data, response) {
console.log(data);
callback();
});
}
就像他的答案中提到的@Anatoliy一样,async.eachSeries
它将帮助您解决for循环问题。它将遍历hashtag
数组,仅在调用callback
函数后才调用下一个项目。
解决这些延迟的技巧是setTimeout
在中的回调searchTwitter
和中的完成回调中调用函数eachSeries
。像这样:
async.whilst(
function () { return true }, // true makes more sense than 0 == 0, especially from a readability standpoint
function (callback) {
async.eachSeries(hashtag, function(tag, callback) {
searchTwitter(tag, function() {
setTimeout(callback, 2000); // Wait 2 seconds before going on to the next tag
})
}, function(err) {
setTimeout(callback, 10000); // Wait 10 seconds before looping over the hashtags again
});
},
function (err) {
}
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句