【发布时间】:2019-06-13 22:21:33
【问题描述】:
在我的一个 API 端点中,我从 Web 获取一个 json 资源 (1) 并对其进行编辑以满足我的需要。在树的“最低”或“最深”部分,我试图获取另一个资源并将其添加到最终的 json 对象中。我对 async/await 比较陌生,但我正在尝试摆脱“旧”Promises,因为我看到了使用 async/await 的优势(或收益)。
(1)中的对象看起来像;
const json = {
date,
time,
trips: [{
name,
legs: [{
id
},
{
id
}
]
}]
};
这是我“重新格式化”和更改 json 对象的方法;
{
date,
time,
trips: json.trips.map(trip => formatTrip(trip))
};
function formatTrip(trip) {
return {
name,
legs: trip.legs.map(leg => formatLeg(leg))
};
};
async function formatLeg(leg) {
const data = await fetch();
return {
id,
data
};
};
问题在于,在我“重新格式化/编辑”原始 json 以查看我想要的方式(并运行所有 format... 函数)之后,legs 对象为空 {}。
我认为这可能是由于 async/await 承诺没有完成。我还读到,如果子函数使用 async/await,则所有高级函数也必须使用 async/await。
为什么?我怎样才能重写我的代码才能工作并看起来不错?谢谢!
编辑:
我根据 Randy 的回答更新了我的代码。 getLegStops(leg) 仍然未定义/为空。
function formatLeg(leg) {
return {
other,
stops: getLegStops(leg)
};
};
function getLegStops(leg) {
Promise.all(getLegStopRequests(leg)).then(([r1, r2]) => {
/* do stuff here */
return [ /* with data */ ];
});
};
function getLegStopRequests(leg) {
return [ url1, url2 ].map(async url => await axios.request({ url }));
};
【问题讨论】:
标签: javascript function async-await axios