I\'ve taken a look at a few questions on recursion in promises and am confused on how to implement them properly:
If you look at your code as long as i
is less than 10 you are recursing and never resolving the promise. You eventually resolve a promise. but it is not the promise the initial caller gets.
You need to resolve with the promise returned by the recursion. How the system works if you resolve with a promise it will still not resolve until also the value is resolved:
let i = 0;
const countToTen = () => new Promise((resolve, reject) => {
if (i < 10) {
i++;
console.log("i is now: " + i);
resolve(countToTen());
} else {
resolve(i);
}
});
countToTen().then(() => console.log("i ended up at: " + i));
There was an error in the last part as well. You didn't provide a function to then
so if you would have done something that actually would have waited you would have got the "i ended up at: 0"
first.