title: Why is finally executed before Promise's then?
body: <p>When I execute the following code, the block of code A gets executed before the block of code B.</p>
  
  <pre><code>return new Promise((resolve, reject) =&gt; {
    try {
      resolve()
    } finally {
      // block of code A
    }
  }).then(() =&gt; {
    // block of code B
  })
  </code></pre>
  
  <p>But I don't understand why A is executed first.</p>
  
  <p>The resolution (or rejection) of a promise triggers the <code>then</code> corresponding to it, so I would expect block of code B to be run before block of code A.</p>
  
  <p>From the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow noreferrer">doc</a>:</p>
  
  <blockquote>
    <p>When either of these options (resolve/reject) happens, the associated handlers queued up by a promise's then method are called.</p>
  </blockquote>
  
  <p>I also read this:</p>
  
  <blockquote>
    <p>the executor is called before the Promise constructor even returns the created object</p>
  </blockquote>
  
  <p><em>the executor = the function passed as param to the Promise object.</em></p>
  
  <p>The latter quote makes me think that the <code>try catch</code> can be finished before the resolution or rejection handlers are triggered (before the executor function is returned from the Promise). It would explain that the <code>finally</code> is triggered before the Promise's <code>then</code>.</p>
  
  <p>HOWEVER, I tried making a call to an external API with fetch and <code>await</code>ing for the response before continuing, hoping that the Promise function would widely have the time to return the executor function before the <code>try catch</code> is finished:</p>
  
  <pre><code>return new Promise(async (resolve, reject) =&gt; {
    try {
      await fetch('https://swapi.co/api/people/1/')
      resolve()
    } finally {
      // block of code A
    }
  }).then(() =&gt; {
    // block of code B
  })
  </code></pre>
  
  <p>And it turned out that A was still executed before B. I expected the resolution handler to be triggered before A is executed, since <code>resolve</code> is called before A is executed. But I am wrong, and I don't understand why.</p>
  
  <p>May someone explain me please?</p>