Note: Not a duplicate question of How to always run some code when a promise is fulfilled in Angular.js as that is specific to AngularJS.
I'm looking for something like jQuery's done or AngularJS's finally.
I have a promise that gets resolved or rejected. Whether it was resolved or rejected I'd like to run same function when fulfilled, as this:
var myPromise = new Promise(function(resolve, reject) {
resolve('Success!');
if( something ) {
resolve('ok');
} else {
reject('not ok');
}
});
myPromise.then(function(data) {
var x = 1;
var y = 2;
console.log(data);
}, function(data) {
var x = 1;
var y = 2;
console.log(data);
});
The above code works. The problem is I'm copying the same function twice. I know I could have a named function like this:
var myPromise = new Promise(function(resolve, reject) { ... });
myPromise.then(doWork, doWork);
function doWork(data) {
var x = 1;
var y = 2;
console.log(data);
}
But I'm wondering if there's a way to:
- Write the function once, instead of
myPromise.then(doWork, doWork);
, and.. - Use anonymous function instead of named function. and..