简体   繁体   English

Javascript函数始终返回未定义

[英]Javascript function always return undefined

I have this vue2 code: 我有这个vue2代码:

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. 并且总是返回undefined。 What am I doing wrong? 我究竟做错了什么?

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. 如果要从此方法返回值,则必须从函数中返回promise ,并使用回调在成功时捕获结果。

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

我对vue2一无所知,但我确实知道axiosaxios工作,因此,由于您在promise之外返回returnValue ,因此您的函数正在返回returnValue的当前值,该值是undefined

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. 您需要做出一个Promise,当它解决时,返回该值。

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. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM