3 回答

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

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;
}

TA貢獻1900條經驗 獲得超5個贊
你能試一下嗎:
async testLogin(context, credentials) {
const loginService = new FetchClient();
let d = await loginService.post('login', credentials);
console.log(d);
}
添加回答
舉報