繁体   English   中英

Vue:处理多个API调用的最佳做法

[英]Vue: Best practices for handling multiple API calls

因此,我发现自己在vuex动作中进行了多个API调用,这让我想知道什么是处理这种情况的最佳方法,多个API调用的最佳实践,让我们从我拥有的代码开始。

我有一个动作,我收集了来自不同API端点(后端为laravel)的所有帖子和所有帖子类别,我敢肯定有比我做的更好的方法:

 fetchAllPosts ({ commit }) { commit( 'SET_LOAD_STATUS', 1); axios.get('/posts') .then((response) => { commit('FETCH_ALL_POSTS', response.data.posts ) commit( 'SET_LOAD_STATUS', 2 ); }, (error) => { console.log(error); commit( 'SET_LOAD_STATUS', 3 ); }) axios.get('/postcategories') .then((response) => { commit('FETCH_ALL_POSTCATEGORIES', response.data.postcategories ) commit( 'SET_LOAD_STATUS', 2 ); }, (error) => { console.log(error); commit( 'SET_LOAD_STATUS', 3 ); }) }, 

我想到的方法的第一个问题是,如果第一个API调用失败,但是第二个API调用成功,那么我将获得2的加载状态(此处2等于成功)!

如果第一个和第二个API调用都正确地获取了数据,我只想处理提交,请帮助正在学习的人。

我想您可能想读一下诺言

在您的示例中,您使用的是Axios,它是一个基于Promise的HTTP客户端,它很棒。

使用Promises,您可以执行多个请求,当所有请求成功后,您便可以执行代码。

使用Axios,您可以使用.all来做到这一点,如下所示:

axios.all([getPosts(), getPostCategories()])
  .then(axios.spread(function (posts, categories) {
     // Both requests are now complete
  }));
axios.all([
    axios.get(firstUrl),
    axios.get(secondUrl)
])
.then(axios.spread(function (response1, response2) {
    //response1 is the result of first call
    //response2 is the result of second call
}))
.catch(function (error) {

});

有关catch()的注意事项:在第一个失败的请求上将调用它,而忽略其余的调用。 因此,如果第一个调用失败,则即使没有发出第二个请求也将调用catch()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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