本文介绍了使我的asyncForEach()并行而不是顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我希望循环内的代码同时运行,但循环后的代码仅在处理完循环后才能运行:
So I want the code inside loop to run simultaneously but the code after the loop to run only when loop is done processing:
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
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
*/
推荐答案
使用 Array.prototype.map()
和 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();
这篇关于使我的asyncForEach()并行而不是顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!