Skip to content

Instantly share code, notes, and snippets.

@mfandl
Created March 28, 2018 16:18
Show Gist options
  • Save mfandl/70b90e0c6f03adb75af56a089c0009d2 to your computer and use it in GitHub Desktop.
Save mfandl/70b90e0c6f03adb75af56a089c0009d2 to your computer and use it in GitHub Desktop.
// Output down
const arr = [
{ value: 1 },
{ value: 2 },
{ value: 3 },
undefined,
{ value: 5 },
{ value: 6 }
];
const doubledValue = x => x.value * 2;
const summed = arr.reduce(
(acc, entry) =>
acc
.then(sum => {
const newSum = sum + entry.value;
console.log(`current sum: ${newSum}, current value: ${entry.value}`);
return newSum;
})
.catch(console.log), // this is problematic. since the error is handled here, it does not propagate further
Promise.resolve(0) // either do not catch error here, or if you need to, explicitly return Promise.reject()
);
summed
.then(v => console.log(`Success! Final sum: ${v}`))
.catch(err => console.log(`Summing failed due to an error: ${err}`));
/* OUTPUT
"current sum: 1, current value: 1"
"current sum: 3, current value: 2"
"current sum: 6, current value: 3"
[object Error] {}
"current sum: NaN, current value: 5"
"current sum: NaN, current value: 6"
"Success! Final sum: NaN"
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment