JavaScript .finally()

karel.de.smetoutlook.com's avatar
Published Jul 27, 2021Updated Jun 28, 2023

Returns a new Promise object after the previous promise in the chain has been resolved or rejected. This last part of the chain will execute no matter what.

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours

Syntax

myPromiseObject.then(fulfilledPromiseCallback).finally(finalPromiseCallback);

.finally() can be used with or without .then() and/or .catch().

Example

const myPromise = new Promise((resolve, reject) => {
if (2 + 2 === 4) {
resolve('Fulfilled');
} else {
reject('Rejected');
}
});
myPromise
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(`${err.status} - ${err.errorType}: ${err.message}`);
})
.finally(() => console.log('Operations have ended.'));
/*
Output:
Fulfilled
Operations have ended.
*/

Codebyte Example

In the following example, the callback function passed to finally() is executed when the promise either resolves or rejects.

Code
Output

All contributors

Learn JavaScript on Codecademy

  • A full-stack engineer can get a project done from start to finish, back-end to front-end.
    • Includes 51 Courses
    • With Professional Certification
    • Beginner Friendly.
      150 hours
  • Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
    • Beginner Friendly.
      15 hours