2

我遵循了正确的方法来为承诺编写循环。成功地为 Promise 创建循环。

但是,这种方法似乎不适用于嵌套循环

我要模拟的循环:

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

承诺(注意我在这里简化了 promFunc() 的逻辑,所以不要认为它没用)

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

实际结果:

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

有什么解决办法吗?

4

2 回答 2

1

promWhile返回外部循环需要等待的承诺。您确实忘记了return它,这使得then()结果在外部之后立即解析promFunc()

… function loopbody() {
    return promFunc()
    .then(function() {
        console.log(c);
        c++; // move to top (or in the `then` as below)
        …
        return promiseWhile(
//      ^^^^^^
        … ) // .then(function(){c++});
    }); 
} …
于 2014-07-10T17:35:46.057 回答
0

你会想用它Promise.resolve()代替你的promFunc()它做同样的事情。

于 2016-06-28T23:27:02.250 回答