I've taken a look at a few questions on recursion in promises and am confused on how to implement them properly:
- Recursive Promise in javascript
- AngularJS, promise with recursive function
- Chaining Promises recursively
- Javascript Recursive Promise
I put together a simple example (see below) - this is just an example so I can understand how to make recursion with promises work and not a representation of the code in which I'm working.
Net-net, I'd like the promise to resolve, but according to the output on node, it doesn't resolve. Any insight into how to make this resolve?
var i = 0;
var countToTen = function() {
return new Promise(function(resolve, reject) {
if (i < 10) {
i++;
console.log("i is now: " + i);
return countToTen();
}
else {
resolve(i);
}
});
}
countToTen().then(console.log("i ended up at: " + i));
And the output on the console:
> countToTen().then(console.log("i ended up at: " + i));
i is now: 1
i is now: 2
i is now: 3
i is now: 4
i is now: 5
i is now: 6
i is now: 7
i is now: 8
i is now: 9
i is now: 10
i ended up at: 10
Promise { <pending> }
The promise never resolves.