javascript - promise 的嵌套 while 循环

标签 javascript node.js promise bluebird

我已关注帖子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++;
}

Promised (注意,我在这里简化了 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

有什么解决办法吗?

最佳答案

promWhile 返回外循环需要等待的 promise 。您确实忘记了 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++});
    }); 
} …

关于javascript - promise 的嵌套 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24682808/

相关文章:

javascript - 意外的响应代码 : 200

javascript - Express 应用程序不听没有端口

用于聊天应用程序的 Python 或 Node

javascript - 无法读取未定义的 mysql 的属性 'typeCast'

javascript - 附加到具有重复类的 div

javascript - ajax 和 javascript 的区别

javascript - 用纯css模拟mouseenter

javascript - JavaScript 中大数的除法和余数

javascript - 在 Angular 应用程序的路由中的解析中创建 promise

javascript - 如何使用 promise 返回在 nodejs 的快速路由器中递归编辑的对象数组?