我想寻求帮助!
我正在尝试对每个数组元素发出发布请求。
问题是我需要积累每个帖子响应的答案,然后将count数组返回给调用函数。 我认为我的基本问题是返回的计数为0(已初始化),换句话说,发布请求尚未完成,答案已经返回。
我还认为我的代码太嵌套了,我需要帮助以简化请求
谢谢
function gt({ username, startDate, endDate }) {
const query = '....' //never mind here
client.request(query, { username:arguments[0],
startDate:arguments[1],
endDate:arguments[2]})
.then((response)=>{
//response here is ok and what i expect then i want to send the response for proccesing and get the answer back in categories
let count = getCategories(response["transactions"]);
// here is the wanted result should be in the returned answer
console.log(count);
})
.catch((err)=>{console.log(err)});
}
function getCategories(transactions){
let count = CATEGORIES; /// some json with keys and values
Object.keys(count).forEach(v => count[v] = 0) /// zero the values
for (var i=0;i<transactions.length;i++){
let transaction= transactions[i];
axios.post(SERVER_URL, {
transDescription: transaction["description"]
})
.then( function (response) {
let category = response.data["transactionCategory"];
console.log(category)
count[category]+= transaction["amount"];}) //accumulating in count and then return when loop finishes
.catch(function (error) {
console.log(error);
});
}
return count;
}
调用gt函数:
gt('some username','some date','some date');
// i expect to get the count variable here and print it
答案 0 :(得分:0)
实际上,您的[
{
"value_one_new_name": "Y",
"value_two_new_name": "12",
"key": "123"
},
{
"value_one_new_name": "N",
"value_two_new_name": "2",
"key": "123"
},
{
"value_one_new_name": "Y",
"value_two_new_name": "35",
"key": "456"
}
]
循环在任何for
请求完成并且其诺言得以解决之前就结束了。
此外,您可能希望您的axios
函数实际上返回一些值:对计数的承诺。
我建议使用gt
和async
,它们对于带有异步代码的循环非常实用。
注意:await
是替代方法,但是您可能几乎同时发送了许多请求。
Promise.all
在function gt({ username, startDate, endDate }) {
const query = "...";
return client.request(query, {
// ^^^^^^
username:arguments[0],
startDate:arguments[1],
endDate:arguments[2]
}).then((response) => {
let categories = getCategories(response["transactions"]);
console.log(categories);
return categories; // <----
}).catch((err) => {
console.log(err);
});
}
async function getCategories(transactions) {
//^^^
let count = CATEGORIES;
Object.keys(count).forEach(v => count[v] = 0);
for (var i = 0; i < transactions.length; i++) {
let transaction = transactions[i];
let response = await axios.post(SERVER_URL, {
// ^^^^^^^^^^^^^^^^^^^^
transDescription: transaction["description"]
});
let category = response.data["transactionCategory"];
console.log(category)
count[category] += transaction["amount"];
}
return count;
}
上还需要另一条注释:您的代码使该对象结构发生了变化。如果您第二次调用此函数并再次使用CATEGORIES
,则可能是“危险的”:在这种情况下,以前的结果将被覆盖。每次初始化CATEGORIES
时,实际上要复制一份会比较谨慎:
count