vue:语法错误: await 是一个保留字

新手上路,请多包涵
async checkDriver(mobile) {
    this.$axios({
      url: "xxx",
      method: "POST",
      data: {
        mobile: mobile
      }
    }).then(res => {
      console.log("========="+res.status);
      return res.data.status;
    }).catch(error => {
      this.$message.error(error.toString());
      return -1;
    });
  },
  addValidate() {
    this.$refs['form'].validate((valid) => {
      if (valid) {
        let status = await this.checkDriver(this.form.mobile);
        console.log(status);

      } else {
        return false;
      }
    });

未解析的变量或类型等待。突出显示可能打算异步但缺少异步修饰符的函数。如何在 => 中使用等待?给我一些帮助。谢谢

原文由 woki 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

async 关键字必须用于其主体中使用 await 的函数。

因此,将 asynccheckDriver 移动到 addValidate

 checkDriver(mobile) {
    // ...
}
async addValidate() {
    // ...
    let status = await this.checkDriver(this.form.mobile);
}

此外, checkDriver 方法应该返回一个承诺。因此,将 checkDriver 的内容更改为:

 checkDriver(mobile) {
    return this.$axios({
        url: "xxx",
        method: "POST",
        data: {
            mobile: mobile
        }
    })
}

并且从 Promise 返回的数据(在本例中为 axios)将分配给 statusaddValidate

然后,如果你想处理错误,你应该将 await 调用包装在 try/catch 块中。

原文由 skovmand 发布,翻译遵循 CC BY-SA 4.0 许可协议

 addValidate() {
    this.$refs['form'].validate( async (valid) => {
      if (valid) {
        let status = await this.checkDriver(this.form.mobile);
        console.log(status);

      } else {
        return false;
      }
    });

您可以在参数旁边添加缺少的 async 关键字

原文由 Isaac 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题