【问题标题】:Return Response After For loop in Node Js?Node Js中的For循环后返回响应?
【发布时间】:2021-10-27 03:23:15
【问题描述】:

我正在尝试从我的数据库中获取用户,然后遍历它们并在外部服务器中获取每个用户余额,该服务器以每个用户的余额进行响应。我过滤响应并将我需要的数据推送到一个数组中。最后我应该将此数组发送到客户端。下面的代码将说明这一点

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




})

当我调试代码时,我发现我总是发送带有空数组的响应,甚至在进入其余代码之前。我想在获取所有数据后发送响应

【问题讨论】:

    标签: node.js express http response


    【解决方案1】:

    我可以看到一些问题:

    • 您在 users.forEach() 循环中定义 var body = [];
    • 在终止 res.send() 之前,您无需等待 ExternalServer.GetPriceOfAsset()ExternalServer.GetAssetsOfUser() 调用来解决他们的承诺。
    • 您根本没有处理任何错误,尽管我没有在下面的代码中添加任何内容来解决这个问题。

    我认为解决方案类似于以下内容,尽管我们当然不能自己运行它来确定。

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

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 2020-09-19
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2017-02-06
      • 2021-12-14
      • 2016-02-25
      • 1970-01-01
      相关资源
      最近更新 更多