Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Promise.prototype.finally()

BaselineWidely available

Thefinally() method ofPromise instances schedules a function to be called when the promise is settled (either fulfilled or rejected). It immediately returns anotherPromise object, allowing you tochain calls to other promise methods.

This lets you avoid duplicating code in both the promise'sthen() andcatch() handlers.

Try it

function checkMail() {  return new Promise((resolve, reject) => {    if (Math.random() > 0.5) {      resolve("Mail has arrived");    } else {      reject(new Error("Failed to arrive"));    }  });}checkMail()  .then((mail) => {    console.log(mail);  })  .catch((err) => {    console.error(err);  })  .finally(() => {    console.log("Experiment completed");  });

Syntax

js
promiseInstance.finally(onFinally)

Parameters

onFinally

A function to asynchronously execute when this promise becomes settled. Its return value is ignored unless the returned value is a rejected promise. The function is called with no arguments.

Return value

Returns a newPromise immediately. This new promise is always pending when returned, regardless of the current promise's status. IfonFinally throws an error or returns a rejected promise, the new promise will reject with that value. Otherwise, the new promise will settle with the same state as the current promise.

Description

Thefinally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

Thefinally() method is very similar to callingthen(onFinally, onFinally). However, there are a couple of 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.
  • TheonFinally callback does not receive any argument. This use case is for precisely when youdo not care about the rejection reason or the fulfillment value, and so there's no need to provide it.
  • Afinally() call is usually transparent and reflects the eventual state of the original promise. So for example:
    • UnlikePromise.resolve(2).then(() => 77, () => {}), which returns a promise eventually fulfilled with the value77,Promise.resolve(2).finally(() => 77) returns a promise eventually fulfilled with the value2.
    • Similarly, unlikePromise.reject(3).then(() => {}, () => 88), which returns a promise eventually fulfilled with the value88,Promise.reject(3).finally(() => 88) returns a promise eventually rejected with the reason3.

Note:Athrow (or returning a rejected promise) in thefinally callback still rejects the returned promise. For example, bothPromise.reject(3).finally(() => { throw 99; }) andPromise.reject(3).finally(() => Promise.reject(99)) reject the returned promise with the reason99.

Likecatch(),finally() internally calls thethen method on the object upon which it was called. IfonFinally is not a function,then() is called withonFinally as both arguments — which, forPromise.prototype.then(), means that no useful handler is attached. Otherwise,then() is called with two internally created functions, which behave like the following:

Warning:This is only for demonstration purposes and is not a polyfill.

js
promise.then(  (value) => Promise.resolve(onFinally()).then(() => value),  (reason) =>    Promise.resolve(onFinally()).then(() => {      throw reason;    }),);

Becausefinally() callsthen(), it supports subclassing. Moreover, notice thePromise.resolve() call above — in reality,onFinally()'s return value is resolved using the same algorithm asPromise.resolve(), but the actual constructor used to construct the resolved promise will be the subclass.finally() gets this constructor throughpromise.constructor[Symbol.species].

Examples

Using finally()

js
let isLoading = true;fetch(myRequest)  .then((response) => {    const 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((json) => {    /* process your JSON further */  })  .catch((error) => {    console.error(error); // this line can also throw, e.g. when console = {}  })  .finally(() => {    isLoading = false;  });

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-promise.prototype.finally

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp