嵌套while循环承诺
我已经按照正确的方式编写了许诺的循环。 为成功创build承诺循环。
但是,似乎这种方法不适用于嵌套循环
我想要模拟的循环:
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
任何解决scheme
promWhile
返回外部循环需要等待的承诺。 你忘了return
它,这使得then()
结果立即在外部的promFunc()
之后被parsing。
… function loopbody() { return promFunc() .then(function() { console.log(c); c++; // move to top (or in the `then` as below) … return promiseWhile( // ^^^^^^ … ) // .then(function(){c++}); }); } …
你会想使用Promise.resolve()
而不是你的promFunc()
它做同样的事情。