简体   繁体   English

在 Vue.js 中连续调用两个 API

[英]Two API call in a row in Vue.js

I have an app in Vue.js where user can post a review on a selected restaurant.我在 Vue.js 中有一个应用程序,用户可以在其中对选定的餐厅发表评论。 To "POST" a review I have two functions linked to on @click event:要“发布”评论,我在@click事件上链接了两个函数:

  <button          
  class="btn btn-sm btn-primary mt-2 mr-2"
  @click="addRestaurant(), addReview()"
  >Add a Review</button>

Here is my two functions:这是我的两个功能:

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 })
    },

It does work most of the time but I am facing two problems:它在大多数情况下都有效,但我面临两个问题:

-If a restaurant instance allready exists, it throws a HTTP 400 error in my console. - 如果一个餐厅实例已经存在,它会在我的控制台中抛出一个HTTP 400 error I've tried to catch it but with no success.我试图抓住它,但没有成功。

-It seems that sometimes addReview() is execued before addRestaurant() and I get an error because this.$route.params.maps has a ForeignKey constraint. - 似乎有时 addReview() 在 addRestaurant() 之前执行,我得到一个错误,因为this.$route.params.maps有一个 ForeignKey 约束。

So I tried to make only one function, with my two functions inside, trying to make addReview() executing as soon as addRestaurant() is done but I couldn't find a way.所以我试着只制作一个 function,里面有我的两个函数,试图让addReview()addRestaurant()完成后立即执行,但我找不到方法。 I also tried to make an if statement to check if my restaurant instance existed but I don't know if making so much API call in a row is good practice.我还尝试创建一个 if 语句来检查我的餐厅实例是否存在,但我不知道连续调用这么多 API 是否是一种好习惯。

Any help is welcome I you think about the right solution to handle my problem欢迎任何帮助我你认为正确的解决方案来处理我的问题

This my API service:这是我的 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 };

First of all, in your handleResponse you can throw an error if something is wrong.首先,在您的 handleResponse 中,如果出现问题,您可以抛出错误。 That way, the error will end up in the catch method of the fetch call:这样,错误将最终出现在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();    
  }
}

If handleresponse goes well, the fetch call will return a promise, but you're not handling that promise when you call apiService .如果 handlerresponse 运行良好,则 fetch 调用将返回 promise,但当您调用 apiService 时,您并未处理该apiService I think it should look something like this:我认为它应该看起来像这样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM