【问题标题】:query properites from promise object and save in variable从 promise 对象查询属性并保存在变量中
【发布时间】:2019-06-20 21:45:22
【问题描述】:

我正在使用 axios 获取请求,并返回 response.data 的对象。但我希望能够查询 response.data 的属性并将其保存为变量并在另一个类中使用。

export class myClass {
    public async getData() {
        return axios.get(url)
            .then(response => response.data)
            .catch((error) => {
                console.log(error);
            });
        }
    }

我想从响应中访问这些属性,并保存为值:

response.data.name
response.data.address
response.data.company

我可以通过控制台记录属性,但如果我尝试将其用作某处的值,我会得到未定义。

public async getName() {
    return this.getData().then((response: any) => {
        console.log(response.data.name);
        return response.data.name;
    });
}

致电:

const name = new myClass().getName();
NAME: name(undefined)

【问题讨论】:

    标签: typescript promise axios factory-pattern


    【解决方案1】:

    默认情况下,async 函数返回一个Promise,你应该这样实现它,更容易理解:

    我的班级

    export class myClass {
        ...
        public async getData() {
            return axios.get(url);
        }
    
        public async getName() {
            try {
                const response = await this.getData();
                return response.data.name;
            } catch (error) {
                // handle errors here
            }
        }
        ...
    }
    

    调用 getName()

    const myClass = new myClass();
    const name = await myClass.getName();
    

    【讨论】:

    • 调用 getName 时出现以下错误:const name = await myClass.getName();,出现错误:await' expression is only allowed within an async function
    • 忘记getData()功能,我会编辑我的帖子
    • const name = await myClass.getName(); 在哪里被调用?如果它在函数中,则需要在前面加上 async
    • 即使在函数中,我仍然无法定义
    • 正如错误消息中所说,您只能在async 函数中使用await 表达式。您应该添加更多关于const name = await myClass.getName(); 使用位置的详细信息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多