call(back)

Predict the Output: A then and finally Chain

The executor calls both reject and resolve. What does the chain log? Explain why.

const p = new Promise((resolve, reject) => {
  reject("first");
  resolve("second");
});

p.finally(() => {
  console.log("finally 1");
  return "ignored";
})
  .then(
    (v) => console.log("then", v),
    (e) => {
      console.log("caught", e);
      return "recovered";
    },
  )
  .finally(() => console.log("finally 2"))
  .then((v) => console.log("then", v));

Hints

Hint 1

A promise settles once: whichever of resolve or reject runs first wins.

Hint 2

finally receives no argument and its return value is discarded, unless it throws or returns a rejected promise.

Solution

Show the approach

Answer: finally 1, caught first, finally 2, then recovered

  • A promise settles once. The later resolve is ignored.
  • finally receives no argument, and its return value is discarded. The original value or reason passes through.
  • finally changes the outcome only if it throws or returns a rejected promise.
  • A rejection handler that returns normally turns the chain back to fulfilled.

Asked at