在使用axios时,同步异步理解较浅时踩的一些坑
一开始是想使用axios.get()从前端向后端发request请求,得到stockId数据,再拿该数据去请求别的网页,但是由于axios是异步请求数据的,导致一直拿不到数据
·
一开始是想使用axios.get()从前端向后端发request请求,得到stockId数据,再拿该数据去请求别的网页,但是由于axios是异步请求数据的,导致一直拿不到数据
第①版代码:
searchId: function () {
if (isNaN(this.stockInfo)) {
axios.get("http://localhost:8080/searchId?name=" + this.stockInfo).then(
(res) => {
this.stockId = res.data.data;
console.log("searchId函数: " + res.data.data);
}
)
} else {
this.stockId = this.stockInfo;
}
},
submit: function () {
this.searchId();
console.log("submit函数: " + this.stockId);
浏览器控制台的结果:
很明显 ,因为异步请求,导致先执行的submit函数,并且值为null,没有拿到值;
而searchId函数在慢悠悠执行完之后返回了一个 正确的值(没用)。
第②版代码:
searchId: function () {
if (isNaN(this.stockInfo)) {
return axios.get("http://localhost:8080/searchId?name=" + this.stockInfo).then(
(res) => {
console.log(res)
console.log("searchId函数: " + res.data.data)
return res.data.data;
}
)
} else {
return this.stockInfo;
}
},
submit: function () {
this.stockId = this.searchId();
console.log("submit函数: " + this.stockId);
控制台的结果:
第③版代码:
searchId: function () {
if (isNaN(this.stockInfo)) {
return axios.get("http://localhost:8080/searchId?name=" + this.stockInfo).then(
(res) => {
console.log(res)
console.log("searchId函数: " + res.data.data)
return res.data.data;
}
)
} else {
return this.stockInfo;
}
},
submit:async function () {
this.stockId = await this.searchId();
console.log("submit函数: " + this.stockId);
控制台的结果:
终于出现了希望的结果,关于为什么submit的结果从Promise变成了整型,参考(8条消息) await把Promise解析为普通对象,async函数return的返回值是promise对象,await后转化为普通Object_async return promise_longlongago~~的博客-CSDN博客
在去学习了同步异步模型之后,于是有了第4、5版代码
第④版代码:
searchId: async function () {
if (isNaN(this.stockInfo)) {
const newVar = await axios.get("http://localhost:8080/searchId?name=" + this.stockInfo);
console.log(newVar)
this.stockId = await newVar;
console.log("searchId函数: " + this.stockId);
} else {
this.stockId = this.stockInfo;
}
},
submit: function () {
this.stockId = this.searchId();
console.log("submit函数: " + this.stockId);
}
控制台的结果:
发现不如预期顺序,仔细思考后发现,这样写就是踩了一个大坑,执行searchId函数,里面的代码虽然会同步执行,但是这行代码却是异步执行
console.log("submit函数: " + this.stockId);
第⑤版代码:
结合回调函数,最终版
searchId: function () {
if (isNaN(this.stockInfo)) {
const newVar = axios.get("http://localhost:8080/searchId?name=" + this.stockInfo);
console.log(newVar)
return newVar;
} else {
return this.stockInfo;
}
},
submit: async function () {
var resp = await this.searchId();
this.stockId = resp.data.data;
console.log("submit函数: " + this.stockId);
}
控制台的结果:
也得到了想要的结果
总结:折腾测试了这么多次,感觉第③版优于第⑤版
更多推荐
已为社区贡献1条内容
所有评论(0)