yosiweinreb
yosiweinreb

Reputation: 485

Async recursive using promise

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.

Upvotes: 5

Views: 140

Answers (2)

McMath
McMath

Reputation: 7188

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.

Upvotes: 1

Ben Fortune
Ben Fortune

Reputation: 32118

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.
});

Upvotes: 4

Related Questions