Created
August 17, 2020 23:41
-
-
Save devheedoo/2f183948c1c7dbab9e9b93b3715ca8a9 to your computer and use it in GitHub Desktop.
sequential async sum with reduce
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 numbers = [2, 5, 1, 3, 4]; | |
function asyncNumber (n) { | |
return new Promise((resolve, reject) => { resolve(n) }); | |
} | |
async function asyncSum (numbers) { | |
return numbers.reduce(async (prevSum, n) => { | |
const sum = await prevSum; | |
return asyncNumber(sum + n); | |
}, Promise.resolve(0)); | |
} | |
asyncSum(numbers).then(final => console.log('resolved:', final)); | |
// resolved: 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment