【问题标题】:Nested while loop for promise嵌套 while 循环 for promise
【发布时间】:2016-06-29 07:27:02
【问题描述】:

我已经按照Correct way to write loops for promise. 的帖子成功创建了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

有什么解决办法吗?

【问题讨论】:

    标签: javascript node.js promise bluebird


    【解决方案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++});
        }); 
    } …
    

    【讨论】:

    【解决方案2】:

    你会想要使用Promise.resolve() 而不是你的promFunc() 它做同样的事情。

    【讨论】:

      猜你喜欢
      • 2023-03-02
      • 2020-10-09
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-17
      • 2021-08-21
      • 2017-08-08
      • 2017-04-30
      相关资源
      最近更新 更多