为了避免回调地狱,我链接了几个(Bluebird Promise)指令,每个指令都运行一个异步的for循环。当for循环仍在运行时,链不再等待每个for循环完成,而是直接冲到显示“完成”的结尾处。如何更改我的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
});
});发布于 2020-04-13 02:44:06
您不会退还promiseFor创建的Promise。至此,链断开了,.then(function(result2) {不会等待代码完成。您需要在promiseFor(function(count) {前面添加一个return
.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)
})https://stackoverflow.com/questions/61176371
复制相似问题