Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Understanding promise resolutions

Source: developer.mozilla.org

new Promise((resolveOuter) => {
  resolveOuter(
    new Promise((resolveInner) => {
      setTimeout(resolveInner, 1000);
    })
  );
}); 

This promise is already resolved at the time when it’s created
(because the resolveOuter is called synchronously), but it is resolved
with another promise, and therefore won’t be fulfilled until 1 second
later, when the inner promise fulfills.

My Inference: Even a pending promise counts as a resolved promise therefore the statement

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this promise is already resolved at the times it’s created

My Question: How does resolveOuter being called synchronously affect the resolution of a promise? Is it the mere fact that the newly created promise needs to exist at a certain state? I know I’m missing something deeper here. I’m very new to promises, can somebody please elaborate?

>Solution :

The outer promise calls resolveOuter() immediately (synchronously), BUT you’re calling resolve() with another promise that is still pending. That means it will not yet be resolved until the child promise is also resolved.

So, the outer promise is immediately in the pending state, but it’s watching the inner promise. The inner promise is also immediately in the pending state since it’s been created, but resolve() has not yet been called.

Then, the setTimeout() fires and that resolves the inner promise. The outer promise is watching the inner promise (with the equivalent of .then()) and when it sees that the inner promise resolves, it can then resolve itself.

How does resolveOuter being called synchronously affect the resolution of a promise?

If you were calling resolveOuter() with a static value, then the outer promise would immediately go to the fulfilled state. But, you called resolveOuter(somePendingPromise) so that outer promise is still pending and is waiting for the inner promise to fulfill/reject.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading