一次forEach 中 await 的使用

forEach 和 await/async 的问题

最近在刷面试提的时候看见这样一道题

const list = [1, 2, 3]
const square = num => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(num * num)
        }, 1000)
    })
}

async function test() {
    for (const x of list) {
        const res = await square(x)
        console.log(res)
    }
}
test()
  • 问输出什么,怎么优化间隔1秒输出
输出结果: 1 4 9

然后就试了了一下,同时输出,头疼,为什么呢? 一个大大的问号。好吧接下来找下原因吧

  • 找到问题
    看一下 forEach 实现
if (!Array.prototype.forEach) {
  Array.prototype.forEach = function(callback, thisArg) {
    var T, k;
    if (this == null) {
      throw new TypeError(' this is null or not defined');
    }

    var O = Object(this);
    var len = O.length >>> 0;

    if (typeof callback !== "function") {
      throw new TypeError(callback + ' is not a function');
    }

    if (arguments.length > 1) {
      T = thisArg;
    }
    k = 0;

    while (k < len) {
      var kValue;
      if (k in O) {
        kValue = O[k];
        callback.call(T, kValue, k, O);
      }
      k++;
    }
  };
}
// 在执行时相当于在while 中执行了异步操作
  • 解决办法
//用for...of 或者for循环代替 forEach

async function test () {
  var nums = await getNumbers()
  for(let x of nums) {
    var res = await multi(x)
    console.log(res)
  }
}
posted @ 2021-11-12 09:30  影的记忆  阅读(521)  评论(0编辑  收藏  举报