vue2中,promise.all调用接口的用法
在 Vue 中,可以使用 Promise.all() 方法来调用多个接口,并在所有接口返回结果后进行下一步操作。
下面是一个示例,在这个示例中,我们调用了两个接口,分别是 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;
});
}
}
}
在上述代码中,我们在 mounted()
生命周期钩子中调用了 Promise.all()
方法,并传入了一个包含两个 Promise 的数组。这两个 Promise 分别是调用 getUserInfo()
和 getOrderList()
方法返回的 Promise。在 Promise.all()
的回调函数中,我们使用了 ES6 的数组解构语法,将两个 Promise 的返回值分别保存到 userInfo
和 orderList
中。
在 getUserInfo()
和 getOrderList()
方法中,我们使用了 Axios 库来发送 HTTP 请求,并返回 Promise 对象。在请求成功后,我们从响应中提取出数据并返回。
需要注意的是,在使用 Promise.all() 方法时,如果其中一个 Promise 返回了错误,则整个 Promise.all() 的返回值也会是错误,因此需要在调用 Promise.all() 方法后使用 .catch() 方法来处理错误。