然后不是axios async / await发布请求上的功能

时间:2018-07-15 08:49:20

标签: javascript asynchronous vue.js axios ecmascript-7

我正在通过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);
  }
}

1 个答案:

答案 0 :(得分:3)

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关键字返回一个Promise。因此,您应该这样调用函数:

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