JS关于async await一个巨难的问题

代码如下

// 构造一个Promise对象
function timeout(ms){
  return new Promise((res,rej)=>{
    setTimeout(()=>{
      res()
    },ms)
  })
}

// 假定一个数组
const arr = [1,2,3]

// async函数
async function run(){
  arr.forEach(async ()=>{
    await timeout(1000)
  })
  console.log( '3秒过去了' )
}

run()

我希望‘3秒过去了’应该在3秒后打印出来,而上述代码运行后会瞬间打印

看下哪位大神能最先解决我的这个难题,以最优解者为胜,若差不多则以最先解出者为胜。

前提条件:必须使用arr.forEach,必须使用async await
阅读 3.1k
3 个回答
async function run(){
  for (let i of arr){
    await timeout(1000)
  }
  console.log( '3秒过去了' )
}

建议直接用for of 代替 forEach,一定要用forEach得另外去封装一个函数 得不偿失


//用MDN的Polyfill加上async await用了有坑别找我
Array.prototype.forEach = async 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];
      await callback.call(T, kValue, k, O);
    }
    k++;
  }
};
async function run(){
 await arr.forEach(async ()=>{
    await timeout(1000)
  })
  console.log( '3秒过去了' )
}

你是对forEach有什么误解。。。它并不会等传入的异步函数执行结束再遍历下一个元素。

问题提的确实符合你的名字,感觉在说相声

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题