javascript - 如何使用承诺并稍后在我的代码中使用结果?
问题描述
我是异步操作和 js 的新手。这是我的问题。我有一个 Person 类。我想使用从 API 调用中获得的数据来初始化 Person 实例。
class Person {
constructor(data) {
this.data = data;
}
}
我正在使用 Axios 进行 API 调用。我收到了回复,并想在我的课堂上使用它。
const res = axios.get('https://findperson.com/api/david');
const david = new Person(res);
我明白 res 在这个阶段是一个承诺,我需要消费它。我该怎么做?我怎样才能得到响应并正确使用它?
解决方案
axios.get() 返回一个对象的承诺,其中包含返回的数据、状态、标题等...
async function getPerson() {
try {
const res = await axios.get('https://findperson.com/api/david');
const david = new Person(res.data);
// do something with david
} catch (error) {
console.log(error)
}
}
或者
function getPerson() {
axios
.get('https://findperson.com/api/david')
.then(res => {
const david = new Person(res.data)
// do something with david
})
.catch(console.log)
}
推荐阅读
- asp.net-core-3.1 - 从 Microsoft.Identity.Web 登录/注销捕获事件
- svg - 如何配置在 sveltekit 中使用 svg 文件?
- amazon-web-services - 与外部相比,同一 VPC 内部的 AWS 网络负载均衡器粘性表现不同
- regex - 正则表达式只允许文本字段中的数字和破折号
- javascript - 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串长度超过 maxJsonLength 上设置的值
- terraform - 部署组的 Cloudformation 到 Terraform 的转换
- java - JComboBox:用自定义 JPopupMenu 替换弹出窗口?
- javascript - Nuxt.js - 在 axios 插件中访问存储状态
- python - 如何将指数值转换为图表中的 Int
- r - 如果字符串与不同列中的多个字符串匹配,则从列中子集字符串