我正在尝试从一个端点获取数据,并使用它在将数据发送到前端之前命中另一个端点。我已经尝试了许多不同的异步等待组合,但是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#
答案 0 :(得分:0)
代码在记事本中产生了“感觉”,因此应将其视为提示而不是解决方案。
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;
});