First, analyze the following code:

function test() {
    const arr = [1.2.3.4.5];
    arr.forEach(async (item) => {
      const res = await new Promise((resolve, reject) = > {
        setTimeout(() = > {
          resolve(item);
        }, 2000);
      });
      console.log(res);
    });
    console.log("ss");
}
Copy the code

ForEach and console.log(” SS “) are serial, so this code prints ss first and 1, 2, 3, 4, 5 simultaneously.

In practice, we usually want to first traverse the array to obtain data, and then operate the data. Specifically, in the last example, we want to output 1, 2, 3, 4, 5, and then output SS. The code of array traverse to obtain data may be serial or parallel, which needs to be determined according to the specific situation. You can’t use the forEach function.

Use for… of… To realize the serial

async function test() {
    const arr = [1.2.3.4.5];
    for(const item of arr){
        const res = await new Promise((resolve, reject) = > {
          setTimeout(() = > {
            resolve(item);
          }, 2000);
        });
        console.log(res);
    }
    console.log("ss");
}
Copy the code

It will output 1, 2, 3, 4, 5, and then ss at intervals of 2s.

Use promise.all for parallelism

async function test() {
    const arr = [1.2.3.4.5];
    await Promise.all(
      arr.map(async (item) => {
        const res = await new Promise((resolve, reject) = > {
          setTimeout(() = > {
            resolve(item);
          }, 2000);
        });
        console.log(res); }));console.log("ss");
}
Copy the code

It’s going to print 1, 2, 3, 4, 5 at 2s intervals, and then it’s going to print SS.