Promise.prototype.finally()

parameter

The callback function that is invoked when the Promise ends.

The return value

Promise object: A copy of the finally() method is usually returned. But when throw is called in the finally() method, a Promise object in the Rejected state is returned with the specified reason. If a Rejected Promise object is returned, a copy of the rejectedPromise object is returned.

describe

When the Promise ends, the callback function provided in Finally () is executed, whether the state is fulfilled or Rejected. Because there is no way to know whether the state of the Promise object is fulfilled or Rejected, the callback function has no parameter value. This method is useful when we are hoping for a function, whether the final state of a Promise is a pity or Rejected.

example

const p1 = Promise.resolve(1);

const p2 = p1.finally(() = > {});

p2; // Promise {<fulfilled>: 1}

p1 === p2; // false
Copy the code
const p1 = Promise.resolve(1);

const p2 = p1.finally(() => {
  return new Error(2);
});

p2; // Promise {<fulfilled>: 1}
Copy the code
const p1 = Promise.resolve(1);

const p2 = p1.finally(() = > {
  throw new Error(1);
});

p2; // Promise {<rejected>: Error: 1}
Copy the code
const p1 = Promise.resolve(1);

const p2 = Promise.reject(2);

const p3 = p1.finally(() = > {
  return p2;
});

p3; // Promise {<rejected>: 2}
Copy the code