The vue axios then function returns a value that cannot be obtained.

 upimg(val){
        var self = this  
        var backdata =""
        this.axios.post("/upload/Upload", val)
          .then(response => {
            if (response.data.code === 0) {
                  this.backdata=response.data.data
                  console.log(this.backdata)
                  console.log(backdata)
            }
            console.log(response.data)
          }
        )
        console.log(this.backdata)
        console.log(backdata)
        returun backdata
      }

want to use the function with parameters to get the return value, but I don"t know why I can"t get the value? The output backdata is all undefined

how should I assign a value to backdata?

Oct.13,2021

ajax post is asynchronous. Post is not finished. Of course, backdata is empty. Just write it this way.


async function upimg(val) {
    console.log('calling');
    let post = ()=>{
        return new Promise(resolve => {
            this.ajax.post('/upload/Upload', val)
                .then(response => {
                    if (response.data.code === 0) {
                        resolve(response.data.data);
                    }
                })
        });
    }
    let result = await post();
    console.log(result);
}

wait for the end of post before returning the value


figure out the asynchronous callback


well, it's not the best result, but I used Promise to solve


self.backdata=response.data.data
this misquoted


two solutions:
1, first of all, the axios method gets a promise, so all you have to do is return axios () in the then of actions

upimg(val){
        return this.axios.post('/upload/Upload', val)
          .then(response => {
            if (response.data.code === 0) {
                 return response.data.data
            }
          }
        )
      }

2. (highly recommended)

async upimg(val){
      const response= await this.axios.post('/upload/Upload', val)
      return response.data.data
      }
Menu