首页 > 解决方案 > 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

标签: node.jsexpresshttpresponse

解决方案


我可以看到一些问题:

  • 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);
  });
});

推荐阅读