最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - vue:Syntax Error: await is a reserved word - Stack Overflow

programmeradmin3浏览0评论
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;
      }
    });

Unresolved variable or type await.Highlights functions that were possibly intended to be async but are missing the async modifier.How to use await in =>?Give me some help.Thanks

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

Unresolved variable or type await.Highlights functions that were possibly intended to be async but are missing the async modifier.How to use await in =>?Give me some help.Thanks

Share Improve this question edited Jun 19, 2018 at 10:10 woki asked Jun 19, 2018 at 9:37 wokiwoki 951 gold badge1 silver badge7 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

The async keyword must be used for the function that USES await in its body.

So, move async from checkDriver to addValidate:

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

Also, the checkDriver method should return a promise. So change the contents of checkDriver to:

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

and the data returned from the Promise (axios in this case) will be assigned to status in addValidate

Then if you want to handle errors, you should wrap the await call in a try/catch block.

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

      } else {
        return false;
      }
    });

You can add the missing async keyword beside the parameter

You must make addValidate() async, like async addValidate() { /* ... */ }. You can only use await in a function that's marked async.

发布评论

评论列表(0)

  1. 暂无评论