【问题标题】:Then is not a function on axios async/await post requestthen 不是 axios async/await post request 上的函数
【发布时间】:2018-12-23 02:43:42
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 谢谢!工作完美。但在我将此标记为答案之前,请您告诉我this 是否是正确的方法?
    • @Sanjay 不,如果您要使用 then(),您应该删除关键字 awaitasync
    • 注意:如果出现错误 --- e.response.data --- 将有实际错误。
    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2019-12-26
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多