title: Javascript, Promise.then return values
body: <p>Doing some research about <code>Promises</code> and I know that a <code>Promise</code> 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 <code>Promise</code> 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.</p>
  
  <p>After the <code>Promise</code> is instantiated we can then add response handler callbacks to the promise by calling the <code>.then</code> function on it. The <code>.then</code> function takes 2 callback functions as its arguments. The first argument is the callback function is called in case the <code>Promise</code> resolve function is called and the second callback is called in case the <code>Promise</code> reject function is called. You can also call <code>.catch</code> on <code>Promises</code> to handle the rejected promises although this is just syntactic sugar for:</p>
  
  <pre><code>.then(undefined, () =&gt; { failure callback})
  </code></pre>
  
  <p>What I find harder to understand is the fact that the <code>.then</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then" rel="nofollow noreferrer">method returns a </a> <code>Promise</code>. For example in the following code:</p>
  
  <h2>Example</h2>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>let random = (Math.random() * 10);
  
  let promise = new Promise((res, rej) =&gt; {
    if (random &gt;= 5) {
      res(random);
    }
  
    rej(random);
  });
  
  
  
  promise
    .then(
      (nr) =&gt; {
        console.log("succes: " + nr);
        return nr + 5;
      })
    .then((nr) =&gt; {
      console.log(nr);
    })
    .catch(
      (nr) =&gt; {
        console.log("failure: " + nr);
      })</code></pre>
  </div>
  </div>
  </p>
  
  <h2>Question:</h2>
  
  <p>In the example at the first <code>.then</code> it returns : <code>nr + 5</code>. In resolve cases of the <code>Promise</code> this value is succesfully passed onto the second <code>.then</code>. How is this possible? Is it under the hood: </p>
  
  <pre><code>return new Promise((res,rej) =&gt; {
      res(nr + 5)
  })
  </code></pre>
  
  <p>or is this caused by something else?</p>