Created
October 23, 2018 08:26
-
-
Save albertodeago/78b1af688b096269282fab6adcd0f46c to your computer and use it in GitHub Desktop.
Using reduce to sequentially handle promises
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
function getInSequence(array, asyncFunc) { | |
return array.reduce((previous, current) => ( | |
previous.then(accumulator => ( | |
asyncFunc(current).then(result => accumulator.concat(result)) | |
)) | |
), Promise.resolve([])); | |
} | |
/** | |
example of use: | |
var a = [1,2,3]; | |
var fun = (param) => { | |
return new Promise((resolve, reject) => { | |
console.log("item " + param); | |
setTimeout(() => { | |
console.log("resolving " + param * 2); | |
resolve(param * 2) | |
}, 1000 ) | |
}) | |
} | |
await getInsequence(a, fun) | |
// output: | |
// item 1 | |
// resolved 2 | |
// item 2 | |
// resolved 4 | |
// item 3 | |
// resolved 6 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment