Why doesn't Array.prototype.forEach () recognize expectation in an asynchronous function just like a for loop?

Using awaitin a loop forinside a function asyncprovides the expected execution result, awaiting the completion of the current Promiseinside 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));
    });
  }

})()
Run code

Why Array.prototype.forEach()doesn’t it provide the same functions as those awaiting execution of the current Promiseone when it is awaitused in 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));
    });
  });
  
})();
Run code
+1
source share
1 answer

await Promise. await for , , , .

forEach , await .

+2

Source: https://habr.com/ru/post/1652783/


All Articles