前提知识点

1、async函数内部 await是阻塞代码
2、多个异步函数await可以 串行改为并行
消除async非必要阻塞

  1. // bad
  2. (async () => {
  3. const getList = await getList();
  4. const getAnotherList = await getAnotherList();
  5. })();
  6. 👇👇👇👇 往下滑动代码块 看good 👇👇👇👇👇
  7. // 阻塞的异步请求 变为并行异步
  8. // good
  9. (async () => {
  10. const listPromise = getList();
  11. const anotherListPromise = getAnotherList();
  12. await listPromise;
  13. await anotherListPromise;
  14. })();
  15. // good
  16. (async () => {
  17. Promise.all([getList(), getAnotherList()]).then(...);
  18. })();

3、foreach迭代中途return是失效的,foreach里的回调函数内部是遍历到该item后立即执行
for of 的的可以return,且 for-of 遍历对象时,先调用遍历对象的迭代器方法 Symbol.iterator,该方法返回一个迭代器对象(迭代器对象中包含一个 next 方法);然后调用该迭代器对象上的 next 方法。
每次调用 next 方法都返回一个对象,其中 done 和 value 属性用来表示遍历是否结束和当前遍历的属性值,当 done 的值为 true 时,遍历就停止了。
所以for of 遍历异步对象时,可以知道每个对象是否结束?

问题

在foreach里传入async的异步函数,期望实现串行的异步调用:

  1. (async function test() {
  2. [1, 2, 3].forEach(async x => {
  3. var res = await later1s(x);
  4. console.log(res);
  5. });
  6. })();
  7. function later1s(data) {
  8. return new Promise((resolve, reject) => {
  9. setTimeout(() => resolve(data), 1000);
  10. });
  11. }
  12. 期望:
  13. 1s 2s 3s
  14. |————|————|————|
  15. 输出 1 2 3
  16. 但实际
  17. 1s 2s 3s
  18. |————|————|————|
  19. 输出 1 2 3

分析

for和forEach的差别是后者不能正常的跳出循环(return、break等),其它的差别不大,把forEach转成for的写法就知道为什么你的for写法可以顺序执行而forEach不能:

foreach 的写法相当于

  1. (async function test() {
  2. [1, 2, 3].forEach(async x => {
  3. var res = await later1s(x);
  4. console.log(res);
  5. });
  6. })();
  7. == 相当于 ==
  8. (async function test() {
  9. // [1, 2, 3].forEach(async x => {
  10. // var res = await later1s(x);
  11. // console.log(res);
  12. // });
  13. // let arr = [1, 2, 3];
  14. let respromise1 = later1s(1);
  15. let respromise2 = later1s(2);
  16. let respromise3 = later1s(3);
  17. console.log(await respromise1);
  18. console.log(await respromise2);
  19. console.log(await respromise3);
  20. })();
  1. (async function test() {
  2. // [1, 2, 3].forEach(async x => {
  3. // var res = await later1s(x);
  4. // console.log(res);
  5. // });
  6. let arr = [1, 2, 3];
  7. for (let i = 0; i < arr.length; i++) {
  8. let res = await later1s(arr[i]);
  9. console.log(res);
  10. }
  11. })();

解决

1、使用for of、for等可中断迭代的代替foreach

参考

当async/await遇上forEach