nodejs应用程序的任务无限执行

Ale*_*sky 2 javascript io node.js

假设我有代码,就像这样

function execute() {
    var tasks = buildListOfTasks();
    // ...
}
Run Code Online (Sandbox Code Playgroud)

buildListOfTask创建函数数组.函数是异步的,可能发出HTTP请求或/和执行数据库操作.

如果任务列表显示为空或执行了所有任务,我需要execute再次重复相同的例程.再说一遍,说"无限循环".所以,它是应用程序的守护进程.

我完全理解如何在sync-world中实现这一点,但有点混淆如何在node.js async-world中实现它.

Pet*_*ons 6

使用async.js和它的队列对象.

function runTask(task, callback) {
    //dispatch a single asynchronous task to do some real work
    task(callback);
}
//the 10 means allow up to 10 in parallel, then start queueing
var queue = async.queue(runTask, 10);

//Check for work to do and enqueue it
function refillQueue() {
  buildListOfTasks().forEach(function (task) {
    queue.push(task);
  });
}    

//queue will call this whenever all pending work is completed
//so wait 100ms and check again for more arriving work
queue.drain = function() {
  setTimeout(refillQueue, 100);
};

//start things off initially
refillQueue();
Run Code Online (Sandbox Code Playgroud)