【发布时间】:2020-01-05 18:36:19
【问题描述】:
我试图在 2 个嵌套循环中找到最低值(“最佳分数”),然后在循环完成后保存结果。以下代码似乎在循环之前而不是之后执行最终保存。
var bestScore = 300;
SaltEdge.getCustomerConnections(customerId, function(res1) {
Promise.all(res1.json.data.map(function(connection) {
return Promise.resolve()
.then(function() {
SaltEdge.getConnectionAccounts(connection.id, function(res2) {
if (res2.json.data) {
return Promise.all(res2.json.data.map(function(account) {
SaltEdge.get3MonthsIncome(connection.id, account.id, function(threeMonthsIncome) {
console.log('threeMonthsIncome', threeMonthsIncome);
var accountScore = SaltEdge.threeMonthsIncomeToScore(threeMonthsIncome);
console.log('account score', accountScore);
if (bestScore > accountScore) bestScore = accountScore;
console.log('best score', bestScore);
return bestScore;
});
}));
}
});
})
.then(function(result) {
return bestScore;
});
})
).then(function(res) {
console.log("i'm here" + bestScore, res);
if (bestScore < 300) {
console.log('--update score', bestScore);
Borrower.update(borrowerId, {salt_edge_score: bestScore}, function() {
done(new Response(200,{ updated: true }));
});
resolve(bestScore);
} else {
done(new Response(200,{ updated: true }));
}
});
});
【问题讨论】:
-
您不能在承诺链的中间插入像
SaltEdge.getConnectionAccounts(connection.id, function(res2) {...});这样的普通回调异步函数。当你这样做时,promise 链将不会在它的回调中等待它或任何东西。您需要在承诺链中承诺所有异步操作,以便正确链接它们。
标签: node.js asynchronous promise async-await