[Vuejs]-Javascript function always return undefined

6πŸ‘

βœ…

If you want to return the value from this method, then you will have to return the promise from the function and use a callback to capture the result on success.

checkUser2() {
    return axios.get(`api/users/CheckUsername/${this.username}`)
      .then(response => response.data.error === 0, errorCallBack => false);
}

And when you call it:

this.checkUser2().then(value => console.log(value))
πŸ‘€Bert

0πŸ‘

I know nothing about vue2, but I do know that axios works on promises, so since you are returning returnValue outside of your promise, your function is returning the current value of returnValue, which is undefined.

0πŸ‘

It is because you are returning the value before the request was made. You need to make a Promise, and when it resolves, return the value.

checkUser2() {
  return new Promise((resolve, reject) => {

    var returnValue;
    axios.get(`api/users/CheckUsername/${this.username}`)
    .then(response => {
      returnValue = response.data.error === 0;
      resolve(returnValue);
    }, errorCallBack => {
      returnValue = false;
      reject(returnValue);
    });
  });
}

Then you just need to call it like this to get the value:

this.checkUser2().then(val => {
 a = val;
})

Hope this helps you.

πŸ‘€Manel Alonso

Leave a comment