Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js nodejs Async:concurency worker在队列中再次推送相同的任务_Node.js_Asynchronous_Concurrency - Fatal编程技术网

Node.js nodejs Async:concurency worker在队列中再次推送相同的任务

Node.js nodejs Async:concurency worker在队列中再次推送相同的任务,node.js,asynchronous,concurrency,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

我想知道在完成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将无限期地一个接一个地添加队列中的所有任务(当任务完成时,相同的任务将添加到队列中)

顺便说一句,你没有在worker函数中调用回调函数

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

非常感谢,我要试试这个!在你回答之前,我正在寻找另一个解决方案。。调用
q.drain
中的函数,再次解析我的
列表
数组,并将任务推送到队列中。不知道哪一个是最好的。。有什么想法吗?顺便说一句,谢谢你的回访,我忘了你的方法不是很有效。例如,如果列表中有3个元素(1,2,3),而您有2个工人,则流程将为:并行执行1&2;do3;再次将元素放入队列中;并行执行1和2;做3等;我的方法的流程是并行执行1&2;并行执行3和1;等等