gpt4 book ai didi

javascript - Node.js:如何防止两个回调同时运行?

转载 作者:太空宇宙 更新时间:2023-11-04 03:07:41 27 4
gpt4 key购买 nike

我对 Node.js 有点陌生。我遇到了一个问题,我想阻止回调在执行时运行。例如:

items.forEach(function(item) {
doLongTask(item, function handler(result) {
// If items.length > 1, this will get executed multiple times.
});
});

如何让 handler 的其他调用等待第一个调用完成后再继续?我正在考虑队列的一些事情,但我是 Node.js 的新手,所以我不太确定该怎么做。有想法吗?

最佳答案

已经有一些库可以处理这个问题,最常用的是 async .

您会对 async.eachSeries() 感兴趣功能。

至于一个实际的例子......

const async = require('async')

async.eachSeries(
items,
(item, next) => {
// Do stuff with item, and when you are done, call next
// ...
next()
},
err => {
// either there was an error in one of the handlers and
// execution was stopped, or all items have been processed
}
)

至于库是如何做到这一点的,你最好看看源代码。

It should be noted that this only ever makes sense if your item handler ever performs an asynchronous operation, like interfacing with the filesystem or with internet etc. There exists no operation in Node.js that would cause a piece of JS code to be executed in parallel to another JS code within the same process. So, if all you do is some calculations, you don't need to worry about this at all.

关于javascript - Node.js:如何防止两个回调同时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34861557/

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