繁体   English   中英

VueJs 中的 Javascript:如何从异步获取而不是 Promise 返回数据对象

[英]Javascript in VueJs: how to return data object from async fetch instead of Promise

我有这个动作

actions: {
    testLogin(context, credentials) {
        const loginService = new FetchClient();
        let d = loginService.post('login', credentials);
        console.log(d);
    },

并且这个函数在另一个类中导入以存储

async post(endpoint, params) {
    await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })
        .then(response => {
            return response.json();
        })
        .then( (data) => {
            this.returnData =  data.data;
        })
        .catch(error => {
            console.log(error);
        });
    return this.returnData;
}

我得到了Promise {<pending>} ,我可以从 fetch 类中提取数据,但如果我在商店中则无法访问数据,因为它是 Promise 而不是对象。 我该如何解决这个问题?

将 return 语句放在第二个then块中:

async post(endpoint, params) {
    await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })
        .then(response => {
            return response.json();
        })
        .then( (data) => {
            this.returnData =  data.data;
            return this.returnData;
        })
        .catch(error => {
            console.log(error);
        });
}

我什至建议您使用以下代码以获得更好的可读性:

async post(endpoint, params) {
    const response = await fetch(this.url + endpoint, {
        'method': 'POST',
        headers: this.headers,
        body: JSON.stringify(params),
    })

    if (!response.ok) {
        const message = `An error has occured: ${response.status}`;
        throw new Error(message);
    }
    
    const resp_data = await response.json()

    return resp_data.data
}

然后像这样调用你的方法:

post(endpoint, params)
    .then(data => {// do something with data})
    .catch(error => {
        error.message; // 'An error has occurred: 404'
    });

请参阅异步/等待指南

你能试一下吗:

async testLogin(context, credentials) {
    const loginService = new FetchClient();
    let d = await loginService.post('login', credentials);
    console.log(d);
}
As @Ayudh mentioned, try the following code:

    async post(endpoint, params) {
    try{
        let response = await fetch(this.url + endpoint, {
            'method': 'POST',
            headers: this.headers,
            body: JSON.stringify(params),
        });
        let data = await response.json();
        this.returnData =  data.data;
    }catch(e){
        console.log(e);
    }
    
    return this.returnData;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM