The Loop problem in async function

Ruan Yifeng"s introduction to ES6-async function

there are two paragraphs:

function dbFuc(db) { // async
  let docs = [{}, {}, {}];

  // 
  docs.forEach(async function (doc) {
    await db.post(doc);
  });
}

//db.postfor

async function dbFuc(db) {
  let docs = [{}, {}, {}];

  for (let doc of docs) {
    await db.post(doc);
  }
}

ask why the three db.post operations of forEach will be executed concurrently , while the for loop will not? Thank you ~


the first way of writing is equivalent to calling the async function three times, and the async function returns promise, immediately rather than waiting for await to complete. The second way of writing is blocking writing, in which await must wait for the execution of the following statements to complete before moving on.


because foreach only calls the callback you passed in and doesn't care about the result

for will not execute the next loop until the code block statement is completed.

Menu