Reputation: 1138
A promise p1
is chained with a thenable that returns a again a chained promise p2
.
p2
is p1
chained with a console.log statement:
p0 = Promise.resolve();
p1 = p0.then(() => {
console.log("Step1");
p2 = p1.then(() => {
console.log("Step2");
});
return p2;
});
I would expect the code to output "Step1" and "Step2". But it only shows "Step1". Can anybody explain, why?
I know that then()
is usually chained like (p0.then(...).then(...)
). So this question is not about change the code so that it runs, but about the reason why it does not work.
Upvotes: 0
Views: 51
Reputation: 370979
You've created promises that depend on each other in order to resolve, so neither resolve.
When you return a Promise from inside a .then
, the Promise that that .then
resolves to will only fulfill when the returned Promise fulfilled. So
p1 = p0.then(() => {
// ...
return p2;
});
means that p1
will only resolve when:
But p2 only resolves after p1 resolves due to
p2 = p1.then(() => {
So neither resolve. Step1 gets logged because p0 resolves, but Step2 doesn't because neither p1 nor p2 resolve.
Upvotes: 4