[英]Two API call in a row in Vue.js
我在 Vue.js 中有一個應用程序,用戶可以在其中對選定的餐廳發表評論。 要“發布”評論,我在@click
事件上鏈接了兩個函數:
<button
class="btn btn-sm btn-primary mt-2 mr-2"
@click="addRestaurant(), addReview()"
>Add a Review</button>
這是我的兩個功能:
addRestaurant () {
let endpoint = `/api/restaurant/`;
let method = "POST";
apiService(endpoint, method, { maps: this.$route.params.maps, adress: this.$route.params.adress, name: this.$route.params.name })
},
addReview () {
let endpoint = `/api/restaurant_review/`;
let method = "POST";
apiService(endpoint, method, { maps: this.$route.params.maps, review_author: 1 })
},
它在大多數情況下都有效,但我面臨兩個問題:
- 如果一個餐廳實例已經存在,它會在我的控制台中拋出一個HTTP 400 error
。 我試圖抓住它,但沒有成功。
- 似乎有時 addReview() 在 addRestaurant() 之前執行,我得到一個錯誤,因為this.$route.params.maps
有一個 ForeignKey 約束。
所以我試着只制作一個 function,里面有我的兩個函數,試圖讓addReview()
在addRestaurant()
完成后立即執行,但我找不到方法。 我還嘗試創建一個 if 語句來檢查我的餐廳實例是否存在,但我不知道連續調用這么多 API 是否是一種好習慣。
歡迎任何幫助我你認為正確的解決方案來處理我的問題
這是我的 API 服務:
function handleResponse(response) {
if (response.status === 204) {
return '';
} else if (response.status === 404) {
return null;
} else if (response.status === 400) {
console.log("Restaurant allready added!")
return null;
} else {
return response.json();
}
}
function apiService(endpoint, method, data) {
const config = {
method: method || "GET",
body: data !== undefined ? JSON.stringify(data) : null,
headers: {
'content-type': 'application/json',
'X-CSRFTOKEN': CSRF_TOKEN
}
};
return fetch(endpoint, config)
.then(handleResponse)
.catch(error => console.log(error))
}
export { apiService };
首先,在您的 handleResponse 中,如果出現問題,您可以拋出錯誤。 這樣,錯誤將最終出現在fetch
調用的catch
方法中:
function handleResponse(response) {
if (response.status === 204) {
throw new Error("No data")
} else if (response.status === 404) {
throw new Error("Wrong URL")
} else if (response.status === 400) {
throw new Error("Restaurant already added!")
} else {
return response.json();
}
}
如果 handlerresponse 運行良好,則 fetch 調用將返回 promise,但當您調用 apiService 時,您並未處理該apiService
。 我認為它應該看起來像這樣:
addRestaurant () {
let endpoint = `/api/restaurant/`;
let method = "POST";
let config = { maps: this.$route.params.maps, adress: this.$route.params.adress, name: this.$route.params.name };
apiService(endpoint, method, config)
.then(data => {
console.log("restaurant added!" + data);
// now you can call the add review function
addReview();
})
.catch(error => console.log(error));
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.