node.js - Return Response After For loop in Node Js?
问题描述
i am trying to get users from my database then loop through them and get each user balance in external server that respond with the balance of each user. i filter the response and push the data i need from it into an array. finally i should send this array to Client-side. the following code will illustrate the point
app.get("/usersData", (req, res) => {
var data = [];
Users.find({}).then((users) => {
users.forEach((user) => {
var body = [];
var userObj = { userName: user.userName, assets: [] };
//Call external Server To get User assets amount
ExternalServer.GetAssetsOfUser(user.secretKey).then((assets) => {
var assetsArr = [];
//Loop through the assets and get the one with greater than 50 and check for the price
for (const asset in assets) {
if (asset.amount > 50) {
//Call the server again to get price assets
ExternalServer.GetPriceOfAsset(asset.name).then((price) => {
assetsArr.push({
name: asset.name,
value: +parseFloat(asset.amount).toFixed(4) * price,
});
});
}
}
});
//Add assetsArr to user Assets
userObj.assets = assetsArr;
body.push(userObj);
});
res.send(body);
});
})
when i debug the code i found i always send response with an empty array even before go into the rest of the code. i want to send the response after get all the data
解决方案
我可以看到一些问题:
- 你
var body = [];
在你的users.forEach()
循环中定义 - 在
ExternalServer.GetPriceOfAsset()
终止. _ExternalServer.GetAssetsOfUser()
res.send()
- 您根本没有处理任何错误,尽管我没有在下面的代码中添加任何内容来解决这个问题。
我认为解决方案类似于下面的内容,尽管我们当然不能自己运行它来确定。
app.get("/usersData", (req, res) => {
Users.find({}).then(async (users) => {
// Move this outside of loop
const body = [];
// Using "for" iterator instead of improper async forEach
for ( let i = 0; i < users.length; i++ ) {
const user = users[i];
const userObj = { userName: user.userName, assets: [] };
//Call external Server To get User assets amount
const assets = await ExternalServer.GetAssetsOfUser(user.secretKey);
const assetsArr = [];
//Loop through the assets and get the one with greater than 50 and check for the price
for (const asset in assets) {
if (asset.amount > 50) {
//Call the server again to get price assets
const price = await ExternalServer.GetPriceOfAsset(asset.name);
assetsArr.push({
name: asset.name,
value: +parseFloat(asset.amount).toFixed(4) * price,
});
}
}
//Add assetsArr to user Assets
userObj.assets = assetsArr;
body.push(userObj);
});
res.send(body);
});
});
推荐阅读
- python - 打开受密码保护的excel并找到最后一行并阅读直到|| Python
- javascript - 页面动态加载后如何获取完整的html源代码
- python - 如何在用户使用中间件注销时删除用户
- c++ - 部分模板专业化以展开特定大小的循环
- rest - Postman 是基于 Java 的工具吗?
- npm - Nuxt 在第一次加载时没有加载正确的 css
- matlab - 在matlab中imwrite改变实际的图像数据
- javascript - 为什么画布矩形不扩展?
- google-sheets - 将所有数据合并到一个新工作表中
- c# - SQL to Entity Framework - Not Exists Count & Group by in 语句