首页 > 解决方案 > then 不是 axios async/await post request 上的函数

问题描述

我正在通过POST请求注册用户。

为此,我将 axios 与 async/await 一起使用!但是,我收到register.then is not a function错误。请帮帮我。

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

标签: javascriptasynchronousvue.jsaxiosecmascript-2016

解决方案


关键字等待一个承诺(这await意味着它在内部处理then),但它不返回一个承诺。而是await返回承诺的结果。

因此,做你想做的事情的正确方法是:

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

但是,async关键字返回一个承诺。所以你应该这样调用你的函数:

sendUserData().then(console.log('done'));

推荐阅读