Yuri Morales
Yuri Morales

Reputation: 2498

Javascript function always return undefined

I have this vue2 code:

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

I call it with:

var a = this.checkUser2();
console.log(a);

and it always returns undefined. What am I doing wrong?

Upvotes: 0

Views: 875

Answers (3)

Bert
Bert

Reputation: 82459

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))

Upvotes: 6

Manel Alonso
Manel Alonso

Reputation: 397

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.

Upvotes: 0

relentless-coder
relentless-coder

Reputation: 1536

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.

Upvotes: 0

Related Questions