I tried to extend a promise while its resolution is ongoing.
(async () => {
var p4 = Promise.resolve([3]);
var rec = (s) => {
let x = s.pop();
s.push(x - 1);
if (x > 0) {
console.log(x);
p4.then(rec);
}
};
p4.then(rec);
console.log("result", (await p4)[0]);
})();
My problem is: the recursion works as expected (3, 2, 1 is printed), but the result is 2 instead of 0. It seems to me that the last line just sees the first step of the recursion. It follows only those continuations, which have been added till the resolution starts. Those which are added while the resolution is ongoing are ignored. How to fix this?
2
Answers
p4
andp4.then
are different promises, sincethen()
returns a new promise. Usethen()
together withawait
to wait for yourthen
chain resolution.Also you should return from
rec()
either a chained promise created again withp4.then()
or[0]
as the final chain result. Otherwise your promise is resolved immediately without chaining:Instead of working with
Promise
manually, try usingasync
andawait
like this:Stackless version:
The snippets refuse to run, but I promise it works in a browser console.