使用async、await实现axios请求网络时的同步执行代码
约 359 字大约 1 分钟
2025-08-01
- 编译器:vscode
- 新建
js
文件demo.js
axios 的基础使用
引入 axios: const axios = require('axios');
测试用接口(来自黑马课程,查询到的是假数据):
var weatherList; //node.js不支持中文,直接写"city=北京"报错:Request path contains unescaped characters var url = "http://wthrcdn.etouch.cn/weather_mini?city=" + encodeURI("北京");
使用 axios 请求:
axios .get(url) .then((res) => { weatherList = res.data.data; console.log({ weatherList }); }) .catch((err) => { console.log({ err }); });
不使用 async、await
时
function searchWeather() {
return axios
.get(url)
.then((res) => {
weatherList = res.data.data;
console.log({ weatherList });
})
.catch((err) => {
console.log({ err });
});
}
function run() {
console.log("我将要进行网络请求");
searchWeather();
console.log("我已经网络请求过了");
}
run();
运行结果:
使用 async、await 关键字时
function searchWeather() {
return axios
.get(url)
.then((res) => {
weatherList = res.data.data;
console.log({ weatherList });
})
.catch((err) => {
console.log({ err });
});
}
async function run() {
console.log("我将要进行网络请求");
await searchWeather();
console.log("我已经网络请求过了");
}
run();
也可以直接写:
async function run() {
console.log("我将要进行网络请求");
await axios
.get(url)
.then((res) => {
weatherList = res.data.data;
console.log({ weatherList });
})
.catch((err) => {
console.log({ err });
});
console.log("我已经网络请求过了");
}
run();
运行结果
注意事项
- 语句用
await
修饰时,方法一定要用async
修饰; axios
网络请求在单独的方法中时,一定要return axios.get().then();
因为axios
返回一个promise
,此时await
修饰才有意义。如果没有return
,vscode 将提示await
对此表达式的类型没有影响。