为承诺编写循环的正确方法。
2022-08-30 05:05:12
如何正确构造一个循环来确保以下 promise 调用和链接的记录器.log(res) 在迭代中同步运行?(蓝鸟)
db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise
我尝试了以下方法(来自 http://blog.victorquinn.com/javascript-promise-while-loop )
var Promise = require('bluebird');
var promiseWhile = function(condition, action) {
var resolver = Promise.defer();
var loop = function() {
if (!condition()) return resolver.resolve();
return Promise.cast(action())
.then(loop)
.catch(resolver.reject);
};
process.nextTick(loop);
return resolver.promise;
});
var count = 0;
promiseWhile(function() {
return count < 10;
}, function() {
return new Promise(function(resolve, reject) {
db.getUser(email)
.then(function(res) {
logger.log(res);
count++;
resolve();
});
});
}).then(function() {
console.log('all done');
});
虽然它似乎有效,但我认为它不能保证调用logger的顺序.log(res);
有什么建议吗?