0

I know that Promises in JS are Immutable.

According to: What does it mean for promises to be immutable and their guaranteed value?

A promise is a one-way latch. Once it is resolved with a value or rejected with a reason, its state and value/reason can never change. So, no matter how many times you do .then() on the same promise, you will always get the same result.

So I am confused about this image from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise enter image description here

It looks like after the Promise is either fulfilled or rejected (resolved) it returns a Promise that is (pending). Why is that?

csguy
  • 1,354
  • 2
  • 17
  • 37
  • 1
    That's a horrible graphic. But yes, calling `then()` or `catch()` does *return a **new** promise* whose state is pending until it gets resolved. For a diagram of the state transitions of a single promise, see [here](https://stackoverflow.com/a/29269515/1048572). – Bergi Jun 14 '20 at 19:20
  • Thank you for the great answers. To those who downvoted I would suggest offering some form of constructive criticism. (this isn't reddit) – csguy Jun 14 '20 at 19:47

1 Answers1

3

Every call to .then() or .catch() returns a new promise. That promise will be resolved or rejected depending upon what happens in the .then() or .catch() handler that it derives from when that handler is called. The promise at the start of the chain is indeed immutable, but once someone else calls .then() or .catch() on it, they get a new promise back from each of those calls whose state is determined by what happens inside the code that runs in the .then() or .catch() handler.

When you get that new promise from .then() or .catch() it will always be in the pending state because the code inside the .then() or .catch() has not yet been called (the original promise has not yet called them). Those statements just register handlers on the original promise.

When those handlers are called, they will determine the state of the new promise. If they return a plain value, that new promise will be resolved with that value. If they throw, that new promise will be rejected. If they return a promise, then that new promise will follow the eventual state of that new promise that was returned form the .then() or .catch() handler and it will resolve or reject as that returned promise does.

jfriend00
  • 683,504
  • 96
  • 985
  • 979