Skip to content

Instantly share code, notes, and snippets.

@g8up
Created August 18, 2023 17:40
Show Gist options
  • Save g8up/81a3c63302d5998a4e423746943fd465 to your computer and use it in GitHub Desktop.
Save g8up/81a3c63302d5998a4e423746943fd465 to your computer and use it in GitHub Desktop.
async run forEach and get results
const forEachAsync = async (arr, handler, isSerial = true) => {
if( isSerial ) {
const result = [];
return arr.reduce((acc, val) => {
return acc.then(()=>handler(val))
.then(ret=>{
result.push(ret);
return ret;
});
}, Promise.resolve())
.then(()=>{
return Promise.resolve(result);
});
}
else {
return Promise.all(arr.map(handler))
}
}
// test - case1
forEachAsync([1,2,3], (item)=>{
console.log(item);
})
// test - case2
(
async ()=>{
console.log(
await forEachAsync([1,2,3], async (item)=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
// console.log(item);
resolve(item);
}, Math.random() * 100 )
})
}, false)
)
}
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment