首页 > 解决方案 > 响应在地图外没有变化

问题描述

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

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": []
  }
}

标签: javascriptnode.jsexpressecmascript-6scope

解决方案


尝试使用 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);
})

推荐阅读