【问题标题】:Response does not change outside map响应在地图外没有变化
【发布时间】:2020-07-07 08:20:17
【问题描述】:

我正在为我的大学项目开发​​一个应用程序。在这里,我需要运行很多请求以获取有关巴西一些交易所的信息。在我得到所有结果后,我需要将它们全部返回给用户。

router.get("/", async function(req, res, next) {
  const response = {
    exchanges: {
      Msg: { dtTm: timeConverter() },
      SctyHghstIncrLst: []
    }
  };

  var exchanges_to_await = [
    { id: 775, symb: "VALE3", desc: "Vale S.A." },
    { id: 884, symb: "ITUB4", desc: "Itaú Unibanco" },
    { id: 69, symb: "BBDC4", desc: "Banco Bradesco SA Preference Shares" },
    { id: 1978, symb: "BBDC4", desc: "B3 SA - Brasil Bolsa Balcao" },
    { id: 484, symb: "PETR4", desc: "Petroleo Brasileiro SA Petrobras Preference Shares" },
  ];

  try {
    exchanges_to_await.map(async exchange => {
      let await_response = await axios.get(
        `https://api.cotacoes.uol.com/asset/intraday/list/?format=JSON&fields=price,pctChange,date&item=${exchange.id}&`
      );
      var exchange_done = {
        symb: exchange.symb,
        desc: exchange.desc,
        SctyQtn: {
          curPrc: await_response.data.docs[0].price,
          prcFlcn: await_response.data.docs[0].pctChange
        }
      };
      return response["exchanges"]["SctyHghstIncrLst"].push(exchange_done);
    });
  } catch (error) {
    response["exchangesError"] = error;
  }

  res.send(response);

问题是因为响应没有更新。我认为范围很简单,但我不知道为什么它不起作用。你能帮我找到解决办法吗?

这是我得到的结果

{
  "exchanges": {
    "Msg": {
      "dtTm": "13:36:25 26/2/2020"
    },
    "SctyHghstIncrLst": []
  }
}

【问题讨论】:

    标签: javascript node.js express ecmascript-6 scope


    【解决方案1】:

    尝试使用 Promise.all()

    let promises = exchanges_to_await.map(async exchange => {
        return axios.get('/https://api.cotacoes.uol.com/asset/intraday/list/?format=JSON&fields=price,pctChange,date&item=${exchange.id}&')
            .then(function (await_response) {
                console.log(await_response);
                var exchange_done = {
                    symb: exchange.symb,
                    desc: exchange.desc,
                    SctyQtn: {
                        curPrc: await_response.data.docs[0].price,
                        prcFlcn: await_response.data.docs[0].pctChange
                    }
                };
                response["exchanges"]["SctyHghstIncrLst"].push(exchange_done);
            })
            .catch(function (error) {
                // handle error
                console.log(error);
            })
    })
    Promise.all(promises).then(function (values) {
        res.send(response);
    })
    

    【讨论】:

    • 是的,这和我正在做的一样。也不行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多