问题
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