node.js - Nodejs异步: concurency worker push the same task again in the queue

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

最佳答案

你必须执行递归函数。

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/

相关文章:

javascript - Express js 从 URL 的根部获取参数(不像 req.params 那样简单)

c# - 添加异步时 "Program does not contain a static ' Main ' method suitable for an entry point"

java - 什么时候 Semaphore.availablePermits() 可以返回比构造函数中声明的更多的值?

c++ - WaitForSingleObject 在 XP 中获取他的信号量,但在 Vista 中没有

java - AtomicReferenceArray 的工作原理

node.js - 使用Node JS堆的Elasticsearch查询内存不足

node.js - 如何将 Redis 哈希值转换为 JSON?

javascript - 如何在 NodeJs 中使用请求进行多个 API 调用?

javascript - RxJS +(异步/等待)用于(多事件)用例

ios - 在 Firebase 中,我可以从 .observeSingleEventOfType() 获取已完成执行其代码块的信号吗?