我有一个返回承诺的函数(getCustomer
函数调用REST API从数据库中获取客户信息)。我还有一个要遍历的客户ID数组,对于每个客户ID,我想调用REST API函数以获取其他客户信息。
当我在for循环中调用函数/承诺时,它总是一遍又一遍地返回客户的第一个值。这是因为在执行Promise之后循环仍在继续吗?我该如何解决?
这是我的代码,调用promise函数:
oauthClient.makeApiCall({
url: url + 'v3/company/' + result.companyId + '/reports/CustomerBalanceDetail'
})
.then(function(balanceDetails) {
var balanceDetails = JSON.parse(balanceDetails.body).Rows.Row;
//only return details if some invoices exist
if (balanceDetails.length > 1) {
var overdueInvoices = [];
var today = new Date();
//loop through all customers
for (var i = 0; i < balanceDetails.length; i++) {
if (balanceDetails[i].Header != undefined) { //only loop through the rows which are not the summary
var headerInfo = balanceDetails[i].Header.ColData;
var invoiceInfo = balanceDetails[i].Rows.Row;
//get the customer phone and email based on their id - call REST API to get customr details
getCustomer(senderId, headerInfo[0].id).then(function(result) {
var customerInvoices = {
"customerName": headerInfo[0].value,
"customerId": headerInfo[0].id,
"customerPhone": result.phone,
"customerEmail": result.email,
"invoices": []
}
//loop through all invoices for each customer and add them to the customer invoices list - this is to exclude payments and not overdue invoices
for (var j = 0; j < invoiceInfo.length; j++) {
//Loop through all invoice and log them to console
}
}, function(err) {
console.log(err);
});
}
}
var response = {
"text": "",
"overdueInvoices": overdueInvoices,
}
resolve(response);
} else {
var response = {
"text": "You do not have any overdue invoices. Good job collecting!",
"overdueInvoices": null,
}
resolve(response);
}
})
.catch(function(e) {
console.error(e);
reject(e);
});