我试图从一个端点获取数据,并在将数据发送到前端之前使用它命中另一个端点。我尝试了多种不同的异步等待组合,但是res.status.json始终会在我设法获取getAirport函数进行解析之前进行解析。关于如何获得等待的任何想法?



router.get("", (req, res, next) => {
  sabre
    .get("/v1/lists/supported/cities")
    .then(response => {
      let cities = response.data.Cities;
      let citiesObj = cities.map(city => {
        //console.log('here');
        return {
          name: city.name,
          code: city.code,
          airports: city.Links.map(link => {
            return getAirport(link["href"]);
          })
        };
      });

      res.status(200).json({ message: "ok", data: citiesObj });
    })
    .catch(err => console.log(err));
});

function getAirport(link) {
  let updatedUrl = link.replace(baseUrl, "");
  return sabre.get(updatedUrl);
}

https://stackoverflow.com/questions/ask#

最佳答案

代码在记事本中产生了“感觉”,因此应将其视为提示而不是解决方案。

router.get("", (req, res, next) => {
  sabre
    .get("/v1/lists/supported/cities")
    .then(async response => {
      let cities = response.data.Cities;
      let citiesObj = await Promise.all(cities.map(async city => {
        //console.log('here');
        let airports = await Promise.all(city.Links.map((link) => return getAirport(link["href"]);))
        return {
          name: city.name,
          code: city.code,
          airports: airports
        };
      }));

      res.status(200).json({ message: "ok", data: citiesObj });
    })
    .catch(err => console.log(err));
});


  Working Solution:




router.get("", (req, res, next) => {
  sabre
    .get("/v1/lists/supported/cities")
    .then(response => {
      let cities = response.data.Cities;
      let citiesObj = cities.map(async city => {
        let airports = await Promise.all(city.Links.map((link)=>{

          return getAirport(link['href'])
        })).then(response=>{

          return response;
        });
        return {
          type: 'city',
          name: city.name,
          code: city.code,
          transport:airports
        };
      });
Promise.all(citiesObj).then(cities=>{
  let response = cities.map(cities=>cities);
  res.status(200).json({message:'ok', data: response});

})
    })
    .catch(err => console.log(err));
});
function getAirport(link) {
  let updatedUrl = link.replace(baseUrl, "");
  return sabre.get(updatedUrl).then(response=>{
    return response.data;
  });

关于node.js - 序列答应并合并,然后再推送到res.json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55246773/

10-11 10:41