Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Then is not a function on axios async/await post request

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);
  }
}
like image 361
Damon Avatar asked Dec 06 '22 11:12

Damon


1 Answers

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'));
like image 98
slebetman Avatar answered Dec 10 '22 10:12

slebetman