为了避免回调地狱,我链接了多个(Bluebird Promise)指令,每个指令运行一个异步for循环。而不是等待每个for循环结束,而是在for循环仍在运行时,该链条将立即冲到最后显示“ DONE”的位置。我如何更改我的for循环,以便在执行下一个“ 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
创建的承诺。至此,链断了,.then(function(result2) {
不等待该代码完成。