JS: Promise .prototype .finally

By Xah Lee. Date: .

(new in JS: ECMAScript 2018)

xpromise.finally(onSettles)
  • xpromise is a promise object.
  • onSettles is optional. It must be a function. No parameter.

call onSettles when xpromise settles (fulfilled or rejected).

returns a new promise that has the same state as xpromise, unless if onSettles throws an error or returns a rejected promise, the state is rejected.

Example. resolve

Promise.resolve(42)
 .then((x) => console.log("fulfilled with value:", x))
 .catch((x) => console.log("caught problem with value:", x))
 .finally(() => {
  console.log("finally called.");
 });
// fulfilled with value: 42
// finally called.

Example. finally throws

const final_prom = Promise.resolve(42)
 .then(
  (x) => console.log("fulfilled with value:", x),
  (x) => console.log("rejected with value:", x),
 )
 .finally(() => {
  console.log("finally called.");
  throw (new Error("omg, got a error in finally."));
 });
// fulfilled with value: 42
// finally called.

final_prom.then(
 (x) => console.log("final_prom, fulfilled with value:", x),
 (x) => console.log("final_prom, rejected with value:", x),
);
// final_prom, rejected with value: Error: omg, got a error in finally.

Example. reject

Promise.reject(17)
 .then((x) => console.log("fulfilled with value:", x))
 .catch((x) => console.log("caught problem with value:", x))
 .finally(() => {
  console.log("finally called.");
 });
// caught problem with value: 17
// finally called.