如何返回映射 TypeScript 中 Promise 结果的 Promise?
我有一个方法可以发出返回一些 JSON 数据的请求。
async borgs(): Promise<Borg[]> {
const response = await fetch("api.example.com/borgs");
return await response.json();
}
问题是,JSON 具有复杂的结构,并且数据包含不相关的元数据字段,因此我想映射结果以返回一个纯 Borg
数组,并丢弃不相关的字段。
async borgs(): Promise<Borg[]> {
const response = await fetch("api.example.com/borgs");
const json = await response.json();
return json.data.borgs.map(borg => ({
goodBorgField: borg.fields.goodBorgField,
}));
}
我无法让它持续工作。有时我会明白
Uncaught (in promise) TypeError:
borg.fields is undefined
为什么,如何使用 async/await 解决这个问题?
响应数据示例:
{
"data": {
"borgs": [
{
"fields": {
"goodBorgField": "value1",
"_badBorgField": "value2"
}
},
{
"fields": {
"goodBorgField": "value3",
"_badBorgField": "value4"
}
}
]
}
}
期望的输出:解析为的 Promise:
[
{
goodBorgField: "value1",
},
{
goodBorgField: "value3",
},
]
为了完整起见,请输入 Borg
:
interface Borg {
goodBorgField: string;
}
I have a method that makes a request that returns some JSON data.
async borgs(): Promise<Borg[]> {
const response = await fetch("api.example.com/borgs");
return await response.json();
}
The thing is, the JSON has a complex structure, and the data contains irrelevant metadata fields, so I would like to map over the results to return an array of plain Borg
, with the irrelevant fields discarded.
async borgs(): Promise<Borg[]> {
const response = await fetch("api.example.com/borgs");
const json = await response.json();
return json.data.borgs.map(borg => ({
goodBorgField: borg.fields.goodBorgField,
}));
}
I can't get this to work consistently. Sometimes I get
Uncaught (in promise) TypeError:
borg.fields is undefined
Why, and how can I fix this using async/await?
Response data example:
{
"data": {
"borgs": [
{
"fields": {
"goodBorgField": "value1",
"_badBorgField": "value2"
}
},
{
"fields": {
"goodBorgField": "value3",
"_badBorgField": "value4"
}
}
]
}
}
Desired output: a Promise that resolves to:
[
{
goodBorgField: "value1",
},
{
goodBorgField: "value3",
},
]
For completeness, type Borg
:
interface Borg {
goodBorgField: string;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论