为什么Array.prototype.forEach()无法识别与for循环相同的异步函数中的等待状态? [英] Why does Array.prototype.forEach() not recognize await within an async function the same as a for loop?

查看:58
本文介绍了为什么Array.prototype.forEach()无法识别与for循环相同的异步函数中的等待状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆