Created
August 18, 2023 17:40
-
-
Save g8up/81a3c63302d5998a4e423746943fd465 to your computer and use it in GitHub Desktop.
async run forEach and get results
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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