如何在axios.post外部获取返回的response,避免变量为undefined问题
核心原因
Axios.post 是异步网络请求,不会阻塞后续同步代码的执行,你写的赋值操作执行时请求还没返回,自然拿不到response值。
你的代码实际执行顺序是:
- 声明变量
newresults,初始值为undefined - 发起
axios.post请求,请求在后台运行,直接跳过回调继续执行后续代码 - 执行
newresults = response,此时请求尚未返回,response未定义,赋值无效 - 执行
console.log(newresults),输出undefined - 请求响应返回后,才会进入
.then回调,此时才能拿到正确的response值
解决方法
方法1:将赋值和后续操作放入.then回调
var newresults axios.post(mainurl, data) .then(function (response) { // 所有需要用到response的操作都要放在回调内部 newresults = response console.log(newresults) // 在这里继续处理newresults的后续逻辑 }) .catch(function (error) { console.log(error); });
方法2:使用async/await语法简化异步逻辑(更推荐)
需要将代码放在async函数中,或使用顶层await:
// 外层必须是async函数,如果你是在模块环境可以直接用顶层await async function fetchData() { var newresults try { const response = await axios.post(mainurl, data) newresults = response console.log(newresults) // 后续处理逻辑 } catch (error) { console.log(error) } } // 调用函数执行请求 fetchData()
内容的提问来源于stack exchange,提问作者historicsoup1
相关产品推荐
相关产品推荐

