js方法里axios请求无返回(undefined)的问题

utils.js,checkAccess方法里,axios请求去查询用户权限,在then里面去返回response的数据。
然后在其他模块调用这个方法: var result = checkAccess(UIItems.AdminMenu),但是拿不到返回值,一直说是undefined…

想了好久,都没有意识到,axios请求是异步的,请求一旦发送出去,浏览器就会继续执行后面的代码,那会儿根本还没有得到server的response呢…

害…脑子那会儿可能是冻住了

import axios from "axios"

export function checkAccess(uiElement){
axios.get("/api/someurl/checkPermission ", {
            params: { uiElement }
        })
      .then(res => {
      	return res.data;
      })
      .catch(err => {
        console.log(err);
        return false
      });
 }

把checkAccess方法改一下,直接返回axios.get()…,也就是一个Promise对象,然后在调用的地方去拿返回值。

import axios from "axios"

export function checAccess(uiElement){
    return(axios.get("/api/someurl/checkPermission ", {
            params: { uiElement }
        }));
}
checkAccess(UIItems.AdministrationMenu)
      .then(res => {
        if (res.data === true) {
        // do something if user has access to admin menu
        }
      })
      .catch(err => {
        console.log(err);
      });

另外做一个记录,供日后参考(push和pop好说,但是总分不清unshift 和 shift)

//add elements into the array from beginning
this.menuArray.unshift(Admin, Statistic);

//return and delete the 1st element of array
this.menuArray.shift();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章