Search code examples
javascriptnode.jscallbackpromisees6-promise

Javascript, Promise.then return values


Doing some research about Promises and I know that a Promise object can be in three states (pending, resolved, rejected). The logic responsible for each of these three states is in a callback function which gets passed into the Promise constructor. This callback function has 2 functions as its arguments resolve and reject which are called when this callback either results in success or failure.

After the Promise is instantiated we can then add response handler callbacks to the promise by calling the .then function on it. The .then function takes 2 callback functions as its arguments. The first argument is the callback function is called in case the Promise resolve function is called and the second callback is called in case the Promise reject function is called. You can also call .catch on Promises to handle the rejected promises although this is just syntactic sugar for:

.then(undefined, () => { failure callback})

What I find harder to understand is the fact that the .then method returns a Promise. For example in the following code:

Example

let random = (Math.random() * 10);

let promise = new Promise((res, rej) => {
  if (random >= 5) {
    res(random);
  }

  rej(random);
});



promise
  .then(
    (nr) => {
      console.log("succes: " + nr);
      return nr + 5;
    })
  .then((nr) => {
    console.log(nr);
  })
  .catch(
    (nr) => {
      console.log("failure: " + nr);
    })

Question:

In the example at the first .then it returns : nr + 5. In resolve cases of the Promise this value is succesfully passed onto the second .then. How is this possible? Is it under the hood:

return new Promise((res,rej) => {
    res(nr + 5)
})

or is this caused by something else?


Solution

  • It is the behaviour of a promise, it is described here

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    In Return value section:

    if the handler function returns a value, the promise returned by then gets resolved with the returned value as its value;