为什么Array.prototype.forEach()无法识别与for循环相同的异步函数中的等待状态? [英] Why does Array.prototype.forEach() not recognize await within an async function the same as a for loop?
问题描述
在async
函数内的for
循环中使用await
可提供执行的预期结果,以等待迭代中当前Promise
的完成
Using await
in a for
loop within an async
function provides the expected result of the execution awaiting the completion of the current Promise
within the iteration
const story = [1,2,3,4,5];
(async() => {
for (var i = 0; i < story.length; i++) {
await new Promise(function(resolve) {
setTimeout(function() {
resolve(story[i])
}, 1000)
}).then(function(chapter) {
document.body
.appendChild(document.createTextNode(chapter));
});
}
})()
当在传递给.forEach()
的回调中使用await
时,为什么Array.prototype.forEach()
不提供与等待当前Promise
履行相同的功能?
Why does Array.prototype.forEach()
not provide the same functionality of awaiting the fulfillment of the current Promise
when await
is using within the callback passed to .forEach()
?
const story = [1,2,3,4,5];
(async() => {
story.forEach(async function(chapterUrl) {
// does not await for Promise fulfillment
await new Promise(function(resolve) {
setTimeout(function() {
resolve(chapterUrl)
}, 1000)
}).then(function(chapter) {
document.body
.appendChild(document.createTextNode(chapter));
});
});
})();
推荐答案
await
暂停当前函数,直到解析Promise
为止.在for
循环中使用多个await
调用时,它们都在同一块范围内执行,因此,请等待上一个调用完成,然后再继续.
await
suspends the current function until the Promise
is resolved. When using multiple await
calls in a for
loop, they are all executed within the same block scope and, thus, wait for the previous one to finish before continuing.
使用forEach
函数时,循环的每次迭代都在其自己的范围内运行,因此每个await
对其他循环都没有影响.
When using the forEach
function, each iteration of the loop is run in its own scope, so each await
has no effect on the others.
这篇关于为什么Array.prototype.forEach()无法识别与for循环相同的异步函数中的等待状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!