We often encounter the need to use asynchronous requests in loops, and ES6’s async/await is our sword to make asynchronous programming easier 🗡.

This article summarizes 5 ways to use async/await in loops (you can test the code in the browser console) :

  • Right in front of your bookmark. Right in front of your bookmark. Right in front of your bookmark.
  • The cross method ❌ : means that all asynchronous requests are executed only through a loop, with no guarantee of order, which we call “parallel” for short.

Take as needed, like 👍 and collect 📕

The forEach ❌

So first of all, if you think about traversal, we use forEach a lot, how about forEach? To try ~

First of all, forEach is essentially a wrapper around a for loop.

Array.prototype.forEach = function (callback) {
  for (let index = 0; index < this.length; index++) {
    callback(this[index], index, this)
  }
}
Copy the code

Calling await inside a callback requires that the callback function itself is an async function, so the code in loop + async/await should read:

async function someFunction(items) {
  items.forEach( async(i) => {
     const res = await someAPICall(i);
     console.log('--->', res);
  });
}

function someAPICall(param) {
    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        resolve("Resolved" + param)
      },param);
    })
}

someFunction(['3000','8000','1000','4000']);
Copy the code

Execute in the console, as shown below:

As you can see, forEach has no serial output. ForEach simply executes all requests in parallel.

for… of… ✔

In fact the for… Of meets our serial requirements.

The idea is as follows:

async function printFiles () { let fileNames = ['picard', 'kirk', 'geordy', 'ryker', 'worf']; for (const file of fileNames) { const contents = await fs.readFile(file, 'utf8'); console.log(contents); }}Copy the code

For this example, the code is as follows:

async function someFunction(items) {
 for (const i of items){
     const res= await someAPICall(i)
     console.log('--->', res);
 }
}

function someAPICall(param) {
    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        resolve("Resolved" + param)
      },param);
    })
}

someFunction(['3000','8000','1000','4000']);
Copy the code

The console execution is as follows:

Reduce ✔

Those who have understood [loop] + [asynchronous] must know reduce. It’s the cream of the crop!

The code is as follows:

function testPromise(time) { return new Promise((resolve, reject) => { setTimeout(() => { console.log(`Processing ${time}`); resolve(time); }, time); }); } let result = [3000,2000,1000, 4000].accumulatorpromise nextID) => { return accumulatorPromise.then(() => { return testPromise(nextID); }); }, Promise.resolve()); result.then(e => { console.log("All Promises Resolved !! ✨ ")});Copy the code

We can use the Reduce function to iterate through the array and resolve the Promise in order.

Very clear! Self console experience.

The generator ✔

It’s also possible to use async Generator.

async function* readFiles(files) { for(const file of files) { yield await readFile(file); }};Copy the code

For this example, the code is as follows:

async function* generateSequence(items) {
  for (const i of items) {
    await new Promise(resolve => setTimeout(resolve, i));
    yield i;
  }
}

(async () => {
  let generator = generateSequence(['3000','8000','1000','4000']);
  for await (let value of generator) {
    console.log(value);
  }
})();
Copy the code

Self console experience.

Promise. All ❌

If you don’t care about the order in which asynchronous requests are executed, you can choose promise.all (), where promise.all () can be used in parallel. It also ensures that all your requests have been fulfilled.

async function printFiles () {
  let fileNames = ['picard', 'kirk', 'geordy', 'ryker', 'worf'];
  await Promise.all(fileNames.map(async (file) => {
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }));
}
Copy the code

For this example, the code is as follows:

async function promiseAll(arr) {
  await Promise.all(arr.map(async (i) => {
    await sleep(i)
    console.log('--->', i);
  }))
}

function sleep(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve()
    }, i)
  })
}

promiseAll(['3000','8000','1000','4000'])
Copy the code

Self console experience.


All right.

That’s all for this summary! Mainly is the code part, oneself knock a knock, or run a run, change a change, feel the similarities and differences.

Is the so-called “code time square hate less ah”! 😄 take on demand, like 👍 collect 📕.

Follow my public number [Nuggets Anthony], continue to output……