Make my asyncForEach() Parallel Instead of Sequential

六眼飞鱼酱① 提交于 2021-02-08 08:27:45

问题


So I want the code inside loop to run simultaneously but the code after the loop to run only when loop is done processing:

Code

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()

Output

/* Output
1   - takes 1 sec
2   - takes 1 sec
3   - takes 1 sec
Done
    - total 3 sec
*/

What I want

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

回答1:


Use Array.prototype.map() and Promise.all():

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();


来源:https://stackoverflow.com/questions/63173059/make-my-asyncforeach-parallel-instead-of-sequential

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!