nodejs异步:concurency worker在队列中再次推送相同的任务

时间:2016-01-05 11:49:58

标签: node.js asynchronous concurrency

我想知道在完成对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
    });
}

1 个答案:

答案 0 :(得分:1)

你必须做一个递归函数。

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);
}

这个鳕鱼将无限期地添加队列中的所有任务(当任务完成时,比队列中添加相同的任务)。

顺便说一下......你没有在工人职能部门调用回调

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);