我想知道在使用完 NodeJS 的异步模块后,将新任务无限期地再次推送到队列中的最佳方法是什么?
var q = async.queue(function (task, callback) {
console.log('hello ' + task.name);
doSomeFunction(task.name, function(cb){
callback();
});
}, 2);
q.drain = function() {
console.log('all items have been processed');
}
// add some items to the queue
for (var i in list) {
q.push({name: i}, function (err) {
console.log('finished task');
//***HERE I would like to push indefinitely this task in the queue again
});
}
最佳答案
你必须执行递归函数。
for (var i in list) {
//Put inside an anonymous function to keep the current value of i
(function(item) {
var a=function(item){
q.push({name: item}, function (err) {
console.log('finished task');
//call the function again
a(item)
});
}
a(item)
})(i);
}
此 cod 将无限期地添加队列中的所有任务,一个接一个(当任务完成时,会将相同的任务添加到队列中)。
顺便说一句...您没有在工作函数中调用回调
var q = async.queue(function (task, callback) {
console.log('hello ' + task.name);
//You have to call the callback
//You have 2 options:
doSomeFunction(task.name,callback); //option 1 -> doSomeFunction - asynchronous function
//doSomeFunction(task.name);callback(); //option 2 doSomeFunction - synchronous function
}, 2);
关于node.js - Nodejs异步: concurency worker push the same task again in the queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34611050/