为承诺写循环的正确方法。如何正确构造循环以确保以下内容承诺电话和锁链logger.log(RES)在迭代过程中同步运行?(蓝鸟)db.getUser(email).then(function(res) { logger.log(res); }); // this is a promise我尝试了以下方法http:/blog.victorQun.com/javascript-诺言-时间-循环 )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);有什么建议吗?
3 回答
哆啦的时光机
TA贡献1779条经验 获得超6个赞
我认为它不能保证调用logger.log(Res)的顺序;
resolve
有什么建议吗?
promiseWhile(…, function() { return db.getUser(email) .then(function(res) { logger.log(res); count++; });})…
while
var promiseWhile = Promise.method(function(condition, action) { if (!condition()) return; return action().then(promiseWhile.bind(null, condition, action));});
while
for
var promiseFor = Promise.method(function(condition, action, value) { if (!condition(value)) return value; return action(value).then(promiseFor.bind(null, condition, action));});promiseFor(function(count) { return count < 10;}, function(count) { return db.getUser(email) .then(function(res) { logger.log(res); return ++count; });}, 0).then(console.log.bind(console, 'all done'));
子衿沉夜
TA贡献1828条经验 获得超3个赞
// Given async function sayHifunction sayHi() { return new Promise((resolve) => { setTimeout(() => { console.log('Hi'); resolve(); }, 3000); });}// And an array of async functions to loop throughconst asyncArray = [sayHi, sayHi, sayHi]; // We create the start of a promise chainlet chain = Promise.resolve(); // And append each function in the array to the promise chainfor (const func of asyncArray) { chain = chain.then(func);}// Output:// Hi// Hi (After 3 seconds)// Hi (After 3 more seconds)
- 3 回答
- 0 关注
- 502 浏览
添加回答
举报
0/150
提交
取消