user2127480
user2127480

Reputation: 4741

Nested while loop for promise

I have followed the post Correct way to write loops for promise. to create loops for promise successfully.

However, it seems that this method doesn't work with nested loop

The loop I want to simulate:

var c = 0;
while(c < 6) {
    console.log(c);
    var d = 100;
    while(d > 95) {
        console.log(d);
        d--;
    } 
    c++;
}

Promised (note that I simplified the logic of promFunc() here, so do not assume it is useless) :

var Promise = require('bluebird');
var promiseWhile = Promise.method(function(condition, action) {
    if (!condition()) return;
        return action().then(promiseWhile.bind(null, condition, action));
    }); 

var promFunc = function() {
    return new Promise(function(resolve, reject) {
        resolve(); 
    }); 
};

var c = 0;
promiseWhile(function() {
    return c < 6;
}, function() {
    return promFunc()
        .then(function() {
            console.log(c);

            // nested
            var d = 100;
            promiseWhile(function() {
                return d > 95; 
            }, function() {
                return promFunc()
                    .then(function() {
                        console.log(d);
                        d--;
                    }); 
            })// .then(function(){c++}); I put increment here as well but no dice...

            c++;
        }); 
}).then(function() {
    console.log('done');   
});

Actual result:

0
100
1
99
100
2
98
99
100
3
97
98
99
100
4
96
97
98
99
100
5
96
97
98
99
100
96
97
98
99
96
97
98
96
97
done
96

Any solutions?

Upvotes: 2

Views: 712

Answers (2)

Warren Parad
Warren Parad

Reputation: 4101

You'll want to use Promise.resolve() instead of your promFunc() It does the same thing.

Upvotes: 0

Bergi
Bergi

Reputation: 665486

promWhile returns a promise for which the outer loop needs to wait. You did forget to return it, which made the then() result resolve immediately after the outer promFunc() did.

… function loopbody() {
    return promFunc()
    .then(function() {
        console.log(c);
        c++; // move to top (or in the `then` as below)
        …
        return promiseWhile(
//      ^^^^^^
        … ) // .then(function(){c++});
    }); 
} …

Upvotes: 1

Related Questions