[英]Bluebird Promises: sequential asynchronous execution of chained promises with for-loops inside
为了避免回调地狱,我链接了几个(Bluebird Promise)指令,每个指令都运行一个异步 for 循环。 而不是等待每个 for 循环完成,链直接冲到最后,在 for 循环仍在运行时显示“DONE”。 如何更改我的 for 循环,以便 promise 链在执行下一个“then”部分之前“等待”每个循环完成?
return Object1.Asyncmethod1(param1)
.then(function(result1) {
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 < result1.length;
}, function(count) {
return Object.someOtherAsyncAction(someParam)
.then(function(res) {
return ++count;
});
}, 0)
}).then(function(result2) {
//another for loop just like the one above
}).then(function(result3) {
console.log("DONE");
res.json({
result: result3
});
}).catch(function(err) {
res.json({
result: 'error:' + err
});
});
您不会返回由 promiseFor 创建的promiseFor
。 至此,链条已断开,并且.then(function(result2) {
不会等待该代码完成。您需要在return
promiseFor(function(count) {
.then(function(result1) {
var promiseFor = Promise.method(function(condition, action, value) {
if (!condition(value)) return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
return promiseFor(function(count) {
return count < result1.length;
}, function(count) {
return Object.someOtherAsyncAction(someParam)
.then(function(res) {
return ++count;
});
}, 0)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.