0

Is there a native way to define a single callback that gets called always regardless of fulfillment or rejection?

This is what I have:

myPromise.then(
    function(value) { // fulfillment
        alwaysDoThis();
    },
    function(reason) { // rejection
        alwaysDoThis();
    }
);

This is what I want:

myPromise.then(
    function(value) { // fulfillment or rejection
        alwaysDoThis();
    }
);

The latter will throw an exception in the case of a rejection, so I know it doesn't do what I want.

gfullam
  • 11,531
  • 5
  • 50
  • 64
  • Depends on the promise library. The one shipped by default with ES6 can't do that. Bluebird can. – slebetman Jul 25 '16 at 19:03
  • Just write one function you can reference by name, then pass into both. –  Jul 25 '16 at 19:04
  • I was hoping to avoid a library. Though using one is not an impossibility. – gfullam Jul 25 '16 at 19:04
  • I certainly could write a function to do it. But I was more interested to discover whether something native already exists that I can use. I couldn't find anything in the docs, but I didn't want to assume that the absence of the feature due to the absence of the documentation. – gfullam Jul 25 '16 at 19:05
  • @Zach Is `.finally()` natively available? Can you link to reference? – gfullam Jul 25 '16 at 19:06
  • I deleted my comment aboout `.finally(callback);` while I looked this up... http://www.2ality.com/2014/10/es6-promises-api.html I'm going to try this to see if it's builtin. I don't see it on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise so I'm not too hopeful. – Zach Jul 25 '16 at 19:06
  • @Zach Yeah, I couldn't find docs for it on MDN or anywhere else. It appears that when that 2ality article was written it was a proposal. It must not have made it into the final spec for es2015. Babel won't even transpile it with the `stage0` preset. – gfullam Jul 25 '16 at 19:15
  • I'm looking at this implementation as well... https://gist.github.com/jish/e9bcd75e391a2b21206b – Zach Jul 25 '16 at 19:21
  • `Promise.prototype.finally = function(onResolveOrReject) { return this.catch(function(reason){ return reason; }).then(onResolveOrReject); };` I found this code here: https://gist.github.com/jish/e9bcd75e391a2b21206b Here's a working plunker: http://plnkr.co/edit/3da7EINsQLtQjjCLQDYb?p=preview – Zach Jul 25 '16 at 19:27

0 Answers0