gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 00:15:34 26 4
gpt4 key购买 nike

假设我有这样的代码

function execute() {
var tasks = buildListOfTasks();
// ...
}

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

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

我完全理解如何在同步世界中实现这一点,但对如何在 node.js 异步世界中实现它感到困惑。

最佳答案

使用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();

关于javascript - 无限执行nodejs应用程序的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15886096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com