axios接口请求顺序如何确保多个请求按特定顺序执行?
摘要:简单场景:请根据axios帮我编写一个前端代码来处理异步接口回调地狱的问题,要求提供两个接口,先请求接口1结束后,再请求接口2 办法一:Axios顺序请求处理 import axios from 'axios&
简单场景:请根据axios帮我编写一个前端代码来处理异步接口回调地狱的问题,要求提供两个接口,先请求接口1结束后,再请求接口2
办法一:Axios顺序请求处理
import axios from 'axios';
// 接口1:获取用户基本信息
function fetchUserInfo(userId) {
return axios.get(`/api/user/${userId}`)
.then(response => {
console.log('接口1成功:', response.data);
return response.data; // 将结果传递给下一个then
})
.catch(error => {
console.error('接口1失败:', error);
throw error; // 抛出错误以便后续捕获
});
}
// 接口2:获取用户订单信息
function fetchUserOrders(userId) {
return axios.get(`/api/orders/${userId}`)
.then(response => {
console.log('接口2成功:', response.data);
return response.data;
})
.catch(error => {
console.error('接口2失败:', error);
throw error;
});
}
// 顺序调用两个接口
function fetchUserDataSequentially(userId) {
// 开始请求链
fetchUserInfo(userId)
.then(userInfo => {
// 接口1成功后调用接口2
return fetchUserOrders(userId)
.then(orders => {
// 合并两个接口的数据
return {
userInfo: userInfo,
orders: orders
};
});
})
.then(combinedData => {
console.log('最终数据:', combinedData);
// 这里可以处理合并后的数据
})
.catch(error => {
console.error('请求链中发生错误:', error);
});
}
// 测试调用
const testUserId = 123;
fetchUserDataSequentially(testUserId);
办法二:Axios async/await版本
import axios from 'axios';
async function fetchUserInfo(userId) {
try {
const response = await axios.get(`/api/user/${userId}`);
console.log('接口1成功:', response.data);
return response.data;
} catch (error) {
console.error('接口1失败:', error);
throw error;
}
}
async function fetchUserOrders(userId) {
try {
const response = await axios.get(`/api/orders/${userId}`);
console.log('接口2成功:', response.data);
return response.data;
} catch (error) {
console.error('接口2失败:', error);
throw error;
}
}
// 使用 async/await 的顺序调用
async function fetchUserDataSequentially(userId) {
try {
const userInfo = await fetchUs
