5

So i am trying to transfer my code into the "Promise world", and in many places when i had to "loop" with async functionality - i simply used recursion in such a way

function doRecursion(idx,callback){
    if(idx < someArray.length){
        doAsync(function(){
            doRecursion(++idx,callback)
        });
    }else{
        callback('done!')
    }
}
doRecursion(0,function(msg){
    //...
});

Now i am trying to make the change into the Promise world, and i am quite stuck

var Promise = require('bluebird')
function doRecursion(idx){
    return new Promise(function(resolve){
        if(idx < someArray.length){
            doAsync(function(){
                //... doRecursion(++idx)
                // how do i call doRecusion here....
            });
        }else{
            resolve('done!')
        }
    });
}
doRecursion(0).then(function(msg){
    //...
});

Thanks.

yosiweinreb
  • 475
  • 4
  • 12
  • 2
    `resolve(doRecursion(++idx));` - if you resolve Promise 1 with Promise 2, then Promise 1 will resolve with the resolved value of Promise 2 – Jaromanda X Feb 22 '16 at 12:21
  • Please stop using the [promise constructor anti-pattern](http://stackoverflow.com/q/23803743/918910). This goes for the answers too. – jib Feb 23 '16 at 01:42

2 Answers2

4

I'd go with the Promise.all approach.

What this does is wait until all the promises in the array have resolved. The map will apply the async method to each item in the array and return a promise.

function doAsyncP() {
    return new Promise((resolve) => {
        doAsync(function() {
            resolve();
        });
    });
}

Promise.all(
    someArray.map(doAsyncP)
).then((msg) => {
    //we're done.
});
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80
1

In your recursive function, you can do this:

...
if (idx < someArray.length) {
  doAsync(function() {
    resolve(doRecursion(idx + 1));
   });
} else {
...

In other words, while idx is less than someArray.length, your promise will resolve to another promise, this time the promise returned by calling doRecursion() with an idx incremented by one. The then callback the bottom will not be called until doRecursion resolves to some value other than a promise. In this case, it will eventually resolve with a value of 'done!'.

That said, if you are using promises, you probably don't need to use recursion at all. You might have to refactor your code a bit more, but I would suggest considering @BenFortune's answer as an alternative.

McMath
  • 6,862
  • 2
  • 28
  • 33
  • Bit of an anti-pattern IMO if you're using promises. – Ben Fortune Feb 22 '16 at 12:41
  • @BenFortune Yes, I agree, but it's what the asker asked. I've never even thought about using recursion with promises before, and that is probably why. The asker should consider your accepting your answer instead. – McMath Feb 22 '16 at 12:45