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 thePromise
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
- A
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 withundefined
),Promise.resolve(2).finally(() => {})
will be resolved with2
. - Similarly, unlike
Promise.reject(3).then(() => {}, () => {})
(which will be resolved withundefined
),Promise.reject(3).finally(() => {})
will be rejected with3
.
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
To contribute to this compatibility data, please write a pull request against this repository: https://github.com/mdn/browser-compat-data.
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 |