-
-
Save rogerramosme/a59755420ba70d81b7b9439ae730b4ee to your computer and use it in GitHub Desktop.
An example "always" behavior for ES6 promises. This only works if you do not create / return intermediate 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
// A thing I want to do | |
// This flow only involves **one** promise, for example an ajax call | |
// None of the subsequent `then` or `catch` calls, return new promises. | |
const explode = false; | |
const promise = new Promise((resolve, reject) => { | |
if (explode) { | |
reject(); | |
} else { | |
resolve(); | |
} | |
}).then(() => { | |
console.log('Thing is done. Do followup task.'); | |
return 'my argument'; | |
}).then((arg1) => { | |
console.log('Thing is done. Do followup task 2. argument: ' + arg1); | |
}).catch(() => { | |
console.log('Thing failed'); | |
}).then(() => { | |
console.log('Always do this'); | |
}); | |
// => "Thing is done. Do followup task." | |
// => "Thing is done. Do followup task 2. argument: my argument" | |
// => "Always do this" | |
// Set explode to true | |
const explode = true; | |
const promise = new Promise((resolve, reject) => { | |
if (explode) { | |
reject(); | |
} else { | |
resolve(); | |
} | |
}).then(() => { | |
console.log('Thing is done. Do followup task.'); | |
return 'my argument'; | |
}).then((arg1) => { | |
console.log('Thing is done. Do followup task 2. argument: ' + arg1); | |
}).catch(() => { | |
console.log('Thing failed'); | |
}).then(() => { | |
console.log('Always do this'); | |
}); | |
// => "Thing failed" | |
// => "Always do this" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment