Why does Array.prototype.forEach() not recognize a

2020-03-31 09:26发布

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));
    });
  }

})()

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));
    });
  });
  
})();

1条回答
对你真心纯属浪费
2楼-- · 2020-03-31 09:43

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.

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.

查看更多
登录 后发表回答