OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Why does `promise.finally` execute after its caller's `then`?

  • Thread starter Thread starter typed-sigterm
  • Start date Start date
T

typed-sigterm

Guest
Consider this:


Code:
const a = () => {
  return new Promise((resolve) => {
    resolve(1);
  });
};

const b = () => {
  return new Promise((resolve) => {
    a()
      .then((aR) => {
        console.log(aR);
        resolve(2);
      })
      .finally(() => {
        console.log("A");
      });
  });
};

const c = () => {
  b().then((bR) => {
    console.log(bR);
  });
};

c();

Why it prints 1 2 A, not 1 A 2?



The problem is originally discovered by @rebuilding127 on Segmentfault, a StackOverflow-like Chinese forum. I think it's worth translating & publishing here.

<p>Consider this:</p>
<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>const a = () => {
return new Promise((resolve) => {
resolve(1);
});
};

const b = () => {
return new Promise((resolve) => {
a()
.then((aR) => {
console.log(aR);
resolve(2);
})
.finally(() => {
console.log("A");
});
});
};

const c = () => {
b().then((bR) => {
console.log(bR);
});
};

c();</code></pre>
</div>
</div>
</p>
<p>Why it prints <code>1 2 A</code>, <code>not 1 A 2</code>?</p>
<hr />
<p>The problem is originally discovered by <a href="https://segmentfault.com/u/rebuilding127" rel="nofollow noreferrer">@rebuilding127</a> on <a href="https://segmentfault.com/q/1010000044982365" rel="nofollow noreferrer">Segmentfault</a>, a StackOverflow-like Chinese forum. I think it's worth translating & publishing here.</p>
 
Top