主题
结合 async/await 使用 Axios
在现代 JavaScript 开发中,async/await 可以让异步请求写法更清晰、接近同步代码。结合 Axios 使用,代码可读性大大提升。
1. 基本示例
javascript
import axios from "axios";
async function fetchData() {
try {
const response = await axios.get("https://api.example.com/data");
console.log(response.data); // 获取返回的数据
} catch (error) {
console.error("请求出错:", error);
}
}
fetchData();2. 同时发送多个请求
可以使用 Promise.all 配合 async/await 实现并发请求。
javascript
async function fetchMultiple() {
try {
const [users, posts] = await Promise.all([
axios.get("https://api.example.com/users"),
axios.get("https://api.example.com/posts"),
]);
console.log(users.data, posts.data);
} catch (error) {
console.error("请求出错:", error);
}
}
fetchMultiple();3. 错误处理
结合 async/await,使用 try/catch 捕获请求错误:
- 网络错误
- 响应状态码异常
- 请求超时
javascript
async function safeRequest() {
try {
const response = await axios.get("https://api.example.com/data");
if (response.status === 200) {
console.log("请求成功", response.data);
} else {
console.warn("响应异常", response.status);
}
} catch (error) {
console.error("请求失败:", error.message);
}
}
safeRequest();💡 小提示:async/await 与 Axios 结合使用,使异步请求代码更简洁、逻辑更直观,同时便于统一错误处理和数据解析。