The finally()
method returns a Promise
. When the promise is settled, whether fulfilled or rejected, the specified callback function is executed. This provides a way for code that must be executed once the Promise
has been dealt with to be run whether the promise was fulfilled successfully or rejected.
This lets you avoid duplicating code in both the promise's then()
and catch()
handlers.
p.finally(onFinally); p.finally(function() { // settled (fulfilled or rejected) });
onFinally
Function
called when the Promise
is settled.Returns a Promise
whose finally
handler is set to the specified function, onFinally
.
The finally()
method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.
The finally()
method is very similar to calling .then(onFinally, onFinally)
however there are couple of 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 fulfilled with undefined
), Promise.reject(3).finally(() => {})
will be rejected with 3
.Note: A throw
(or returning a rejected promise) in the finally
callback will reject the new promise with the rejection reason specified when calling throw()
.
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); /* this line can also throw, e.g. when console = {} */ }) .finally(function() { isLoading = false; });
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262) The definition of 'Promise.prototype.finally' in that specification. | Draft |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 63 | 18 | 58 | No | 50 | 11.1 |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | 63 | 63 | No | 58 | 50 | 11.1 | No |
Server | |
---|---|
Node.js | |
Basic support | 10.0.0 |
© 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