Vue2中,Promise.all()调用多个接口的用法
在 Vue 中,可以使用 Promise.all() 方法来调用多个相同 (参数不同) 或者不同的接口,并在所有接口返回结果后进行下一步操作。
示例1:
定义两个不同的接口,分别是 getUserInfo() 和 getOrderList(),并在两个接口返回结果后,将结果保存到组件的 data 中:
export default {data() {return {userInfo: {},orderList: []};},mounted() {Promise.all([this.getUserInfo(), this.getOrderList()]).then(([userInfo, orderList]) => {this.userInfo = userInfo;this.orderList = orderList;}).catch((error) => {console.error(error);});},methods: {getUserInfo() {return axios.get("/api/user/info").then((response) => {return response.data;});},getOrderList() {return axios.get("/api/order/list").then((response) => {return response.data;});}}
}
示例2:
相同的接口,不同的传参,代码封装请求
<script>import { orderList} from '@/API/api_common.js'export default {data() {return {isEdit: false,//是否可编辑viewList: [],//可查看列表editList: [],//可编辑列表};},mounted() {let funcList = []funcList = [this.getQueryOrderList({name:'张三丰'}),[]]if(this.isEdit){funcList[1] = this.getQueryOrderList({name:'张无忌', age:18})}this.handleQueryAllList(funcList)},methods: {// 如果第二个表格可以搜索,搜索后只刷新第二个表格的数据doSearch() {this.handleQueryAllList([[],this.getQueryOrderList({name:'张翠山', age:58}], 'two')//查询哪个接口就传入当前接口,其余默认传[]数组// ‘two’ 传参,用于处理只更新哪个列表的值},getQueryOrderList(data={}, type) {return orderList(data).then((res) => {return res.data.list})},handleQueryAllList(funcList, type){Promise.all(funcList).then(([viewList, editList]) => {console.log(viewList, 'viewList')console.log(editList, 'editList')if (!type){this.viewList= viewList}this.editList= editList}).catch((error) => {console.error(error);})},}
}
</script>
总结:
在上述代码中,第一种方式在 mounted() 生命周期钩子中调用了 Promise.all() 方法,并传入了一个包含两个 Promise 的数组。这两个 Promise 分别是调用 getUserInfo() 和 getOrderList() 方法返回的 Promise。在 Promise.all() 的回调函数中,再使用了 ES6 的数组解构语法,将两个 Promise 的返回值分别保存到 userInfo 和 orderList 中。
在 getUserInfo() 和 getOrderList() 方法中,使用了 Axios 库来发送 HTTP 请求,并返回 Promise 对象。在请求成功后,我们从响应中提取出数据并返回。
第2种方式进一步对第一种代码进行二次封装,更加方便简洁。
需要注意的是,在使用 Promise.all() 方法时,如果其中一个 Promise 返回了错误,则整个 Promise.all() 的返回值也会是错误,因此需要在调用 Promise.all() 方法后使用 .catch() 方法来处理错误。