Promise.prototype.finally()

The finally() method returns a Promise and the passed callback is called once the promise is settled, whether fulfilled or rejected.

Syntax

p.finally(onFinally);

p.finally(function() {
   // settled (resolved or rejected)
});

Parameters

onFinally
A Function called when the Promise is settled.

Return value

Returns a Promise.

Description

The finally method can be useful if you want to do some processing or cleanup once the promise is settled, irrespective of its outcome.

The finally method is very similar to calling .then(onFinally, onFinally) however there are couple differences:

 

  • When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it
  • finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.
  • Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2.
  • Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be resolved with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.

However, please note: a throw (or returning a rejected promise) in the finally callback will reject the new promise with that rejection reason.

 

Examples

let isLoading = true;

fetch(myRequest).then(function(response) {
    var contentType = response.headers.get("content-type");
    if(contentType && contentType.includes("application/json")) {
      return response.json();
    }
    throw new TypeError("Oops, we haven't got JSON!");
  })
  .then(function(json) { /* process your JSON further */ })
  .catch(function(error) { console.log(error); })
  .finally(function() { isLoading = false; });

Specifications

Specification Status Comment
TC39 proposal Stage 3  

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support63 No58 No50 No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic support6363 No58 No50 No

See also

Document Tags and Contributors

 Contributors to this page: marcinkowal2015, fscholz, jsx
 Last updated by: marcinkowal2015,