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

San*_*jay 1 javascript asynchronous vue.js ecmascript-7 axios

我正在通过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);
  }
}
Run Code Online (Sandbox Code Playgroud)

sle*_*man 5

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,async关键字返回一个promise。因此,您应该这样调用函数:

sendUserData().then(console.log('done'));
Run Code Online (Sandbox Code Playgroud)