提问者:小点点

使我的asyncForEach()并行而不是顺序


所以我希望循环内的代码同时运行,但循环后的代码只在循环完成处理时运行:

null

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

const waitFor = (ms, num) => new Promise(r => setTimeout(() => {
  console.log(num)
  r()
}, ms));

const doStuff = async() => {

  await asyncForEach([1, 2, 3], async(num) => {
    await waitFor(1000, num);
  })

  console.log('Done');
}

doStuff()

null

/* Output
1   - takes 1 sec
2   - takes 1 sec
3   - takes 1 sec
Done
    - total 3 sec
*/
/* What I want
    _
1    |
2    | - takes 1 sec
3   _|
Done
    - total 1 sec
*/

共1个答案

匿名用户

使用array.prototype.map()promise.all():

null

const asyncForEach = async (array, callback) => {
  await Promise.all(
    array.map(callback)
  );
};

const waitFor = (ms, num) => new Promise(resolve => {
  setTimeout(() => {
    console.log(num);
    resolve();
  }, ms);
});

const doStuff = async () => {
  await asyncForEach([1, 2, 3], async num => {
    await waitFor(1000, num);
  });

  console.log('Done');
};

doStuff();