The problem of vue-axios async

as shown below, now you want to get the data from the background when the page is loaded, and then give the obtained data to other methods and store it in sessionstorage. That is, the data returned by this background must be obtained before performing subsequent operations. But at present, the global variable device is written like this and the following method is executed before the value is obtained. How to get the background data here and assign a value to device before continuing to execute the subsequent method.

 resolveDevice(){
    let self=this;
    let agentId=this.$route.params.device;
    console.log(agentId);
    let params={
        "clause":{
          "agentId":agentId
        }
    };
    return new Promise((resolve,reject)=>{
        api.getDeviceList(params).then((res)=>{
            console.log(res);
            let device=res.data.data.content[0];
            resolve(device);
        }) 
        .catch((error) => {
            reject(error);
        })
    })
},
async getDeviceInfo(){
  let self=this;
  let device=await self.resolveDevice();
  self.device=device;
  sessionStorage.setItem("device",device);
}
mounted(){
    let self=this;
    console.log(this.$route);
    this.getDeviceInfo();
    console.log(this.device);   //
}
Sep.24,2021

you have used Promise , it seems that you still don't know much about asynchronous things


async mounted() {
    let data = await this.getDeviceInfo()
}

I'm not familiar with asynchrony either, but I think it should be written like this.

Menu