[英]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.