Vue:处理多个API调用的最佳做法 [英] Vue: Best practices for handling multiple API calls

查看:70
本文介绍了Vue:处理多个API调用的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我发现自己在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);},(错误)=>{console.log(错误);commit('SET_LOAD_STATUS',3);})axios.get('/postcategories').then((response)=> {commit('FETCH_ALL_POSTCATEGORIES',response.data.postcategories)commit('SET_LOAD_STATUS',2);},(错误)=>{console.log(错误);commit('SET_LOAD_STATUS',3);})}, 

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

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

解决方案

我认为您可能想阅读有关

First issue with my approach that I can think of is if the first API call fails but the second succeeds I will get a load status of 2 (2 equals success here) !

I only want to procced with the commits if BOTH the first and second API call correctly fetch the data, please help someone who is learning.

解决方案

I think you may want to read about promises.

On your example you are using Axios, which is a Promise based HTTP Client and that's great.

With Promises you can do several requests, and when all requests are successful you can THEN execute code.

With Axios you can do that with .all like this:

axios.all([getPosts(), getPostCategories()])
  .then(axios.spread(function (posts, categories) {
     // Both requests are now complete
  }));

这篇关于Vue:处理多个API调用的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆