Skip to content

Instantly share code, notes, and snippets.

@yllieth
Last active April 25, 2017 22:20
Show Gist options
  • Save yllieth/1b6520d20c7007b396d10be9f1734bae to your computer and use it in GitHub Desktop.
Save yllieth/1b6520d20c7007b396d10be9f1734bae to your computer and use it in GitHub Desktop.
Catching error in chained promises
function fn1(previous) {
console.log('previous: ' + previous, 'current: step1');
return Promise.resolve('step1');
}
function fn2(previous) {
console.log('previous: ' + previous, 'current: step2');
return Promise.reject('step2');
}
function fn3(previous) {
console.log('previous: ' + previous, 'current: step3');
return Promise.resolve('step3');
}
function fn4(previous) {
console.log('previous: ' + previous, 'current: step4');
return Promise.resolve('step4');
}
let promiseList = [
fn1(0),
fn2(0).catch(error => console.log('Error caught at ' + error + ' without stopping the chain')),
fn3(0)
];
Promise.all(promiseList)
.then(result => { console.log(result); return fn4(1); })
.catch(error => console.log('caught: ' + error));
// ----------------------------------------------------------------------------
// This will return the following output in the console
//
// previous: 0 current: step1
// previous: 0 current: step2
// previous: 0 current: step3
// Error caught at step2 without stopping the chain
// ["step1", undefined, "step3"]
// previous: 1 current: step4
//
// If you remove the .catch(error => console.log(...)), all concurrent promises
// will be executed (even fn3()) but stops after : fn4 will never be called:
// previous: 0 current: step1
// previous: 0 current: step2
// previous: 0 current: step3
// caught: step2
function fn1(previous) {
console.log('previous: ' + previous, 'current: step1');
return Promise.resolve('step1');
}
function fn2(previous) {
console.log('previous: ' + previous, 'current: step2');
return Promise.resolve('step2');
}
function fn3(previous) {
console.log('previous: ' + previous, 'current: step3');
return Promise.reject('step3');
}
function fn4(previous) {
console.log('previous: ' + previous, 'current: step4');
return Promise.resolve('step4');
}
fn1()
.then(previous => fn2(previous))
.then(previous => fn3(previous).catch(error => console.warn('error caught on ' + error)))
.then(previous => fn4(previous))
.catch(error => console.log('caught: ' + error));
// ----------------------------------------------------------------------------
// This will return the following output in the console:
//
// previous: undefined current: step1
// previous: step1 current: step2
// previous: step2 current: step3
// error caught on step3
// previous: undefined current: step4
//
// If you remove .catch(error => console.warn(error)), you will get:
//
// previous: undefined current: step1
// previous: step1 current: step2
// previous: step2 current: step3
// caught: step3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment