【问题标题】:Refactor from fetch to await that can yield same result从 fetch 重构为 await 可以产生相同的结果
【发布时间】:2021-12-09 12:08:57
【问题描述】:

所以我将不可重用的获取请求代码 sn-p 转移到我的 API:

let response = await fetch(visitURL, {
 method: 'POST',
 headers: {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + userJWT
 },
 body: JSON.stringify(endingVisit)
});
if (response.ok) {
  let {visitId, createdAt} = await response.json();
  const viewVisitDto = new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`);
return viewVisitDto;
} else {
  throw new Error("deactivated!")
}

我能做到这一点:

axios.post(visitURL, {
  headers,
  body: JSON.stringify(visit)
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
})

但并没有完全从响应中给我visitIdcreatedAt,我不能使用response.okresponse.json()。本质上,我需要删除应该在响应中返回的 visitIdcreatedAt

我也尝试过只使用node-fetch 库,但尽管在 VS 代码中它似乎接受它,但即使我安装了@types/node-fetch,即使我为它创建类型定义文件,TypeScript 也不满意,我的 API 就是不喜欢它。

【问题讨论】:

  • 我不确定你要问的是什么,但是node-fetch 最近在他们的包中切换到了 ES6 模块格式,所以你需要降级到以前的主要版本(2 .xx,我相信)以便能够将它与 TypeScript 和 @types/node-fetch 一起使用。 (或者把你的项目转成模块,可能不太方便。)
  • “对它不满意”/“不喜欢它”并不是我见过的最好的错误报告。问题是什么?你可以await axios.post(...) 就像你等待fetch 一样。响应的 API 不同,因此您可能需要做一些工作并查看文档以查看 response 为您提供了什么...
  • 不明白吗?如果它有效,为什么不直接使用 fetch 版本?..non-reusable fetch request code 甚至不知道这意味着什么。
  • @hayavuk,它也不喜欢2.6.5 版本,这意味着TypeScript 仍在抱怨,我安装了@types/node-fetch 并添加了.d.ts 文件。我什至重新启动了编辑器。
  • @Daniel @types/node-fetch 版本是否与node-fetch 包的版本匹配?

标签: javascript typescript axios


【解决方案1】:

猜猜你想要的是什么

// don't know axios, but if it returns a promise await it
const dto = await axios.post(visitURL, {
      headers,
      body: JSON.stringify(visit)
    }).then((response) => {
      // parse response
      return {resonse.visitId, resonse.createdAt}
    }).then(({visitId, createdAt}) => {
      // form dto (where are other vals)?
      return new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`);
    }).catch((error) => {
      console.log(error);
    })

但是 - 你没有提到医生 ID 和 oldPatientId 来自哪里......你尝试提供更多信息,包括 console.log 的输出和周围的代码

【讨论】:

  • 是的,好像response objest 里面没有createdAt,我得到的是object literal cannot have multiple properties with the same name in strict mode
猜你喜欢
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2014-10-18
  • 1970-01-01
相关资源
最近更新 更多