节点 JS - 循环遍历 POST 请求并与其他数据组合时出现问题



我目前正在用Node JS编写,并试图根据从猫鼬查询收到的结果数量循环访问POST请求。以下是我正在尝试完成的步骤,我目前停留在此列表的第二个任务上。

  1. 从MongoDB查询数据
  2. 对于结果中的每个对象,获取字段并通过 POST 请求将其发送到 API 以获取其他数据
  3. 将 Mongo 数据和来自 API 的数据合并到一个数组中,并将新数据发送回 Mongo。

问题(我认为(在我试图循环访问 API 一定次数。当我只是控制台时.log来自 API 的结果,每个对象都在那里并且看起来是正确的。但是当我尝试包含来自 Mongo 的数据的控制台日志时,我只得到最后一个对象(在本例中是第三个(,而不是所有 3 个对象。这是我下面的代码,有人可以帮助我了解我做错了什么吗?

module.exports.getRevenue = function() {
//set date variables
var dt = new Date();
var thisYear = dt.getFullYear();      
var thisMonth = dt.getMonth() + 1;
var lastMonth = thisMonth - 1;
if (lastMonth == 0) {
thisYear = thisYear - 1;
lastMonth = 12;
}
//pull data for revenue 
Model.aggregate([
//omitting query to make code smaller 
], function (err, result) {
if (err) {
console.log(err);
} else {
//clean up results in case tax settings are not present
cleanResult = [];            
for (i in result) {                              
if (result[i]._id.userInfo.taxSettings) {
cleanResult.push({
"id": result[i]._id.userId,
"pay": result[i].sum,
"status": result[i]._id.userInfo.taxSettings.status,
"exemptions": result[i]._id.userInfo.taxSettings.allowances
})
} else {
cleanResult.push({
"id": result[i]._id.userId,
"pay": "1",
"status": "single",
"exemptions": "0"
});
}
}           
//attempt to pull tax info for each result and combine into 1 array
finalTaxes = [];            
for (i=0; i < cleanResult.length; i++) {
temp = cleanResult[i];  
request.post("https://taxee.io/api/v2/calculate/2020")   
.set('Authorization', 'Bearer api_key_here')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ state:"CA", year: thisYear, pay_rate: temp.pay, filing_status: temp.status, pay_periods: "12", exemptions: temp.exemptions }) 
.then(result2 => {
console.log(result2.body);
console.log(temp[i]);
//commenting out code which doesn't work. But this what I want to do.
// finalTaxes.push({
//         "userId": temp.id,
//         "year": thisYear,
//         "month": thisMonth,
//         "revenue": temp.pay,
//         "federal_tax": tempTax.per_pay_period.federal.amount,
//         "state_tax": tempTax.per_pay_period.state.amount,
//         "fica_tax": tempTax.per_pay_period.fica.amount,
//     }); 
})
.catch(err => {
console.log(err);
})
}                                                  
}        
})
};

下面是 mongo 查询的示例输出,以便您了解我的数据是什么样子的

{id:'32464234325', pay:'1', status:'married', exemptions: '2'},
{id:'97463543252', pay:'4500', status:'single', exemptions: '0'},
{id:'98643253131', pay:'6000', status:'single', exemptions: '1'},

正如威利斯所说,可以使用 Promise.all。
您可以按如下方式重写代码。

const requestJobs = [];         
for (i=0; i < cleanResult.length; i++) {
temp = cleanResult[i];  
requestJobs.push(request.post("https://taxee.io/api/v2/calculate/2020")   
.set('Authorization', 'Bearer api_key_here')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ state:"CA", year: thisYear, pay_rate: temp.pay, filing_status: temp.status, pay_periods: "12", exemptions: temp.exemptions }));
}       
Promise.all(requestJobs)
.then(results => {
const finalTaxes = results.map((result, index) => {
return {
userId : cleanResult[index].id,
year : thisYear,
month : thisMonth,
revenu : cleanResult[index].pay,
tax : result.x.y.z, // you can use result from post request
...
}
})
})
.catch(err => {
console.log('some request failed');
})

最新更新