Skip to content

Instantly share code, notes, and snippets.

@devheedoo
Created August 17, 2020 23:41
Show Gist options
  • Save devheedoo/2f183948c1c7dbab9e9b93b3715ca8a9 to your computer and use it in GitHub Desktop.
Save devheedoo/2f183948c1c7dbab9e9b93b3715ca8a9 to your computer and use it in GitHub Desktop.
sequential async sum with reduce
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