用async-await实现类似Promise.all()的执行效果

使用函数:

awaitAll(fn1, fn2, fn3...)

async function awaitAll(...fnArr) {
  if ({}.toString.call(fnArr[0]) === '[object Array]') {
    fnArr = fnArr[0];
  }
  const fnNum = fnArr.length;
  const promiseArr = [];
  const resultArr = [];
  for (let i = 0; i < fnNum; i++) {
    promiseArr.push(fnArr[i]());
  }
  for (let i = 0; i < fnNum; i++) {
    resultArr.push(await promiseArr[i])
  }
  return resultArr;
}

测试:

function wait(ms) {return new Promise(resolve => setTimeout(() => resolve(), ms));}

async function fn1() {
  await wait(1000);
  console.log('fn1');
  await wait(1000);
  return 'fn1';
}

async function fn2() {
  await wait(3000);
  console.log('fn2');
  return 'fn2';
}

async function fn3() {
  console.log('fn3');
  await wait(2000);
  return 'fn3';
}

function fn4() {
  console.log('fn4');
  return 'fn4';
}

awaitAll(fn1, fn2, fn3, fn4).then(results => {
  console.log(results);
});
// 在3秒后,返回结果列表

你可能感兴趣的:(经验技巧)