2

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?

Community
  • 1
  • 1
user2127480
  • 4,623
  • 5
  • 19
  • 17

2 Answers2

1

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++});
    }); 
} …
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Thx a lot! As a starter of promise, I find it difficult to understand the intricacies in promise. Are there any good tutorials or books you would suggest to read deepen my understanding of promise? – user2127480 Jul 10 '14 at 17:43
  • Check https://github.com/kriskowal/q/wiki/General-Promise-Resources. Of course you're also welcome to read the [great promise question here at SO](https://stackoverflow.com/questions/tagged/promise+javascript?sort=votes) – Bergi Jul 10 '14 at 17:46
0

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

Warren Parad
  • 3,910
  • 1
  • 20
  • 29