[英]Is Array.forEach asynchronous?
According to JavaScript, Node.js: is Array.forEach asynchronous? 根据JavaScript,Node.js:Array.forEach是异步的吗? , Array.forEach is synchronous.
,Array.forEach是同步的。 However, for my code below:
但是,对于下面的代码:
function wait5() {
return new Promise(resolve =>
setTimeout(resolve, 5000));
}
async function main() {
console.log("Start");
[1,2].forEach(async (e) => {
const d = await wait5().then(()=> console.log("5s later") )
})
console.log("This should come last!");
}
main();
The output is: 输出为:
Start
This should come last!
5s later
5s later
with the two "5s later" coming out in rapid succession. 两个“ 5s之后”迅速相继问世。
Why is this the case? 为什么会这样呢?
If I use a normal for
loop: 如果我使用普通的
for
循环:
async function main() {
console.log("Start");
for (let i=0;i<2;i++) {
const d = await wait5().then(()=> console.log("5s later") )
}
console.log("This should come last!");
}
then the result is what I wanted: 那么结果就是我想要的:
Start
5s later
5s later
This should come last!
forEach
is synchronous. forEach
是同步的。 Your particular callback function, however, is not. 但是,您的特定回调函数不是。 So
forEach
synchronously calls your function, which starts its work, once for each entry in the array. 因此,
forEach
为数组中的每个条目同步调用一次函数,函数开始工作。 Later, the work that started finishes asynchronously, long after forEach
has returned. 稍后,在
forEach
返回很久之后,开始的工作异步完成。
The issue is that your callback is async
, not that forEach
is asynchronous. 问题是您的回调是
async
,而不是forEach
是异步的。
In general, when you're using an API like forEach
that doesn't do anything with the return value (or doesn't expect a promise as a return value), either: 通常,当您使用像
forEach
这样的API时,不会对返回值做任何事情(或者不希望将promise作为返回值),或者:
Don't pass it an async
function, or 不要将其传递给
async
函数,或者
Ensure that you handle errors within the function itself 确保在函数本身内处理错误
Otherwise, you'll get unhandled errors if something goes wrong in the function. 否则,如果函数中出现问题,您将得到未处理的错误。
Or of course: 或者,当然:
try
/ catch
block within the async
function to catch and handle/report errors within the function itself. async
函数内使用try
/ catch
块来捕获和处理/报告函数本身内的错误。 It looks like you're declaring an async
function inside of a caller that really doesn't care for that sort of thing, forEach
. 似乎您在调用程序内部声明了一个
async
函数,该函数实际上并不关心forEach
类的事情。 Declaring a function async
makes it promise-like, but that promise is only useful if acted on. 声明一个函数
async
使其类似于promise,但是该promise只有在被执行时才有用。
If you need a promise-aware forEach
, that's something you could implement, though Promise.each
in libraries like Bluebird already do that. 如果你需要一个承诺感知
forEach
,这东西你可以实现,但Promise.each
像蓝鸟图书馆已经做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.