The finally() method returns a Promise
and the passed callback is called once the promise is settled, whether fulfilled or rejected.
p.finally(onFinally); p.finally(function() { // settled (resolved or rejected) });
Function
called when the Promise
is settled.Returns a Promise
.
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:
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.Promise.resolve(2).then(() => {}, () => {})
(which will be resolved with undefined
), Promise.resolve(2).finally(() => {})
will be resolved with 2
.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.
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; });
Specification | Status | Comment |
---|---|---|
TC39 proposal | Stage 3 |
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 63 | No | 58 | No | 50 | No |
Feature | Android webview | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
---|---|---|---|---|---|---|---|
Basic support | 63 | 63 | No | 58 | No | 50 | No |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally