Skip to content

Instantly share code, notes, and snippets.

@bozzmob
Forked from jish/promise.js
Created January 31, 2017 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bozzmob/151542ccfa62c314e9bd30daf1cf6f61 to your computer and use it in GitHub Desktop.
Save bozzmob/151542ccfa62c314e9bd30daf1cf6f61 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.
// 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.
var explode = false;
var promise = new Promise(function(resolve, reject) {
if (explode) {
reject();
} else {
resolve();
}
}).then(function() {
console.log('Thing is done. Do followup task.');
return 'my argument';
}).then(function(arg1) {
console.log('Thing is done. Do followup task 2. argument: ' + arg1);
}).catch(function() {
console.log('Thing failed');
}).then(function() {
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
var explode = true;
var promise = new Promise(function(resolve, reject) {
if (explode) {
reject();
} else {
resolve();
}
}).then(function() {
console.log('Thing is done. Do followup task.');
return 'my argument';
}).then(function(arg1) {
console.log('Thing is done. Do followup task 2. argument: ' + arg1);
}).catch(function() {
console.log('Thing failed');
}).then(function() {
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