亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

VueJs 中的 Javascript:如何從異步獲取而不是 Promise 返回數據對象

VueJs 中的 Javascript:如何從異步獲取而不是 Promise 返回數據對象

白板的微信 2023-07-29 15:37:15
我有這個動作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 而不是對象。我該如何解決這個問題?
查看完整描述

3 回答

?
jeck貓

TA貢獻1909條經驗 獲得超7個贊

將 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'

? ? });


查看完整回答
反對 回復 2023-07-29
?
MYYA

TA貢獻1868條經驗 獲得超4個贊

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;

}


查看完整回答
反對 回復 2023-07-29
?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

你能試一下嗎:


async testLogin(context, credentials) {

    const loginService = new FetchClient();

    let d = await loginService.post('login', credentials);

    console.log(d);

}


查看完整回答
反對 回復 2023-07-29
  • 3 回答
  • 0 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號