最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Then is not a function on axios asyncawait post request - Stack Overflow

programmeradmin6浏览0评论

I am registering user via a POST request.

To do this, I am using axios with async/await! However, I am getting register.then is not a function error. Please help me out.

async sendUserData() {
  try {
    const register = await axios.post('/register', {
      email: this.register.email.trim(),
      password: this.register.password.trim(),
    });
    register.then(
      response => {
        console.log(response);
      }
    );
  } catch (e) {
    console.log(e);
  }
}

I am registering user via a POST request.

To do this, I am using axios with async/await! However, I am getting register.then is not a function error. Please help me out.

async sendUserData() {
  try {
    const register = await axios.post('/register', {
      email: this.register.email.trim(),
      password: this.register.password.trim(),
    });
    register.then(
      response => {
        console.log(response);
      }
    );
  } catch (e) {
    console.log(e);
  }
}
Share Improve this question asked Jul 15, 2018 at 8:49 AxelAxel 5,12118 gold badges76 silver badges147 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 16

The await keywords awaits a promise (that means it internally handles the then) but it does not return a promise. Instead await returns the result of the promise.

Therefore, the correct way to do what you want is:

async sendUserData() {
  try {
    const response = await axios.post('/register', {
      email: this.register.email.trim(),
      password: this.register.password.trim(),
    });

    console.log(response);

  } catch (e) {
    console.log(e);
  }
}

However, the async keyword returns a promise. So you should call your function like this:

sendUserData().then(console.log('done'));
发布评论

评论列表(0)

  1. 暂无评论