VueJs 中的 Javascript:如何从异步获取而不是 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 而不是对象。我该如何解决这个问题?


白板的微信
浏览 181回答 3
3回答

jeck猫

将 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'    });

MYYA

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

梵蒂冈之花

你能试一下吗:async testLogin(context, credentials) {&nbsp; &nbsp; const loginService = new FetchClient();&nbsp; &nbsp; let d = await loginService.post('login', credentials);&nbsp; &nbsp; console.log(d);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript