品牌包包排行榜,seo专员岗位要求,建筑新网,建设网站需要什么设施因axios返回值是异步操作#xff0c;获取返回值时#xff0c;请求操作还未完成#xff0c;就已经执行了赋值#xff0c;导致结果位undefined。错误示例如下#xff1a; 1 2 3 4 5 6 7 8 9 10 function GetData(){ let data; axios.get(请求地址, { p… 因axios返回值是异步操作获取返回值时请求操作还未完成就已经执行了赋值导致结果位undefined。错误示例如下 1 2 3 4 5 6 7 8 9 10 function GetData(){ let data; axios.get(请求地址, { params: param }).then(res { data JSON.stringify(res.data.rows); }).catch(err { console.log(err); }); return data; } const dataGetData();
2.解决方法使用async….awaitasync声明发放为异步方法await等待异步操作执行完毕。 1 2 3 4 5 6 7 8 9 async function GetData() { let data; await axios.get(请求地址, { params: param }).then(res { data JSON.stringify(res.data.rows); }).catch(err { console.log(err); }); return data; }
3.异步方法返回值为promise对象接收时需要通过.then(res{})接受值存在res中。 1 2 3 GetData().then(res { console.log(res); }); 原文链接http://www.dreamload.cn/blog/?p922