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

wok*_*oki 3 javascript vue.js vuejs2

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

未解析的变量或类型 await.Highlights 可能旨在异步但缺少 async 修饰符的函数。如何在 => 中使用 await?给我一些帮助。谢谢

sko*_*and 8

async关键字必须用于使用在它的身上等待功能。

所以,asynccheckDriveraddValidate

checkDriver(mobile) {
    // ...
}
async addValidate() {
    // ...
    let status = await this.checkDriver(this.form.mobile);
}
Run Code Online (Sandbox Code Playgroud)

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

checkDriver(mobile) {
    return this.$axios({
        url: "xxx",
        method: "POST",
        data: {
            mobile: mobile
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

并从无极(在这种情况下Axios公司)返回的数据将被分配给statusaddValidate

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