首页 > 解决方案 > 我们可以在 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())

标签: javascriptnode.jsasync-await

解决方案


推荐阅读