javascript - 我们可以在 javascript 中的类函数上使用 async/await 吗?
问题描述
是否可以在类函数上使用异步等待?我已经阅读了一些我们可以通过向static
函数添加关键字来使用它的地方,但看起来它不起作用。
static async getDetails() { }
class Auto {
async getDetails() {
try{
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
const data = await res.json()
console.log(data)
}catch(err){
console.log('error from fetch : ',err)
}
}
}
const auto = new Auto();
auto.getDetails();
上面的代码正在运行,但实际问题是当我返回结果时它的返回承诺。
class Auto {
async getDetails() {
try{
const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
const data = await res.json()
return data.title;
}catch(err){
console.log('error from fetch : ',err)
}
}
}
const auto = new Auto();
const getTheFinalResult = () =>{
let res = ''
auto.getDetails().then(promStr => res = promStr)
return res;
}
console.log(getTheFinalResult())
解决方案
推荐阅读
- javascript - vue.js 的 CDN 和 ESM 构建是什么?
- oracle - 如何更改 Oracle 中模式的默认表空间
- python - Python模差异答案?
- typescript - 打字稿在导入的包上抛出错误
- python - Python 中 VideoCapture 多摄像头的线程
- c# - 什么时候需要“加载程序集”
- reactjs - 如何在数据网格中放置图标(材质 UI)?如何在 Typescript 中描述它?
- amazon-web-services - AWS RDS 上的 dbms_datapump:ORA-28031:已启用最多 150 个角色
- tcl - Tcl lindex 和 expr:非数字故障
- google-business - 在库中找不到 Google My Business API