Some best practices of async/await in JS loops.

The preparatory work

const entries = {
  foo: 0.bar: 1.baz: 2};const keys = ["foo"."bar"."baz"];

const sleep = (ms) = > new Promise((resolve) = > setTimeout(resolve, ms));

const getValue = (key) = > sleep(1000).then((v) = > entries[key]);
Copy the code

Best Practice 1

Do not use await in forEach, use for loop or other loop without callback instead.

// bad
const run = async(_) = > {console.log('start');
  keys.forEach(async key => {
    const value = await getValue(key);
    console.log(value)
  })
  console.log('end');
};

run();
// start
// end
/ / 0
/ / 1
/ / 2
Copy the code

If you want to perform await serially, use a for loop or any loop without callback.

// good
const run = async(_) = > {console.log('start');
    for (let index = 0; index < keys.length; index++) {
      const key = keys[index]
      const value = await getValue(key)
      console.log(value);
    }
  console.log('end')}; run();// start
/ / 0
/ / 1
/ / 2
// end
Copy the code

Execute await in parallel.

// good
const run = async(_) = > {console.log('start');
  const promises = keys.map(async key => {
    const value = await getValue(key)
    console.log(value);
  });
  await Promise.all(promises)
  console.log('end');
};

run();
// start
/ / 0 1 2
// end
Copy the code

Best Practice 2

Instead of using await in filter and reduce, await the promise array returned by map and then filter or reduce.

filter

const run = async(_) = > {const promises = keys.map(getValue);
  const values = await Promise.all(promises)
  const lessThan1 = keys.filter((key, index) = > {
    const value = values[index]
    return value < 1
  })
  console.log(lessThan1);
};

run();
// ['foo']
Copy the code

reduce

const run = async(_) = > {const promises = keys.map(getValue)
  const values = await Promise.all(promises)
  const sum = values.reduce((sum, value) = > sum + value)
  console.log(sum);
};

run();
/ / 3
Copy the code

Refer to the link

  • JavaScript loops – how to handle async/await (lavrton.com)
  • Zellwk.com/blog/async-…