Reputation: 97
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
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?
Upvotes: 0
Views: 56
Reputation: 707238
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.
Upvotes: 2