如何返回映射 TypeScript 中 Promise 结果的 Promise?

发布于 2025-01-12 19:03:52 字数 1425 浏览 1 评论 0原文

我有一个方法可以发出返回一些 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文