await is a reserved word 问题解决方式

1 async 和 await 的概念,建议看这一篇文章https://www.cnblogs.com/SamWeb/p/8417940.html

我遇到的是在vue element组件里面的,原来的写法是这样的,组件表单校验成功后(createProjectConfirm函数里),先新增一条记录,再刷新列表(handleResult)

handleResult (res) {
        if (res.state !== 0) {
          this.$message({
            message: res.message,
            type: 'warning'
          });
        } else {
          this.$message({
            message: res.message,
            type: 'success'
          });
          this.$refs['projectForm'].resetFields();
          this.dialogFormVisible = false;
          this.getProjectList(1);
        }
      },
      createProjectConfirm () {
        this.$refs['projectForm'].validate((valid) => {
          if (valid) {
            let param = {
              projectName: this.projectForm.projectName,
              projectDescription: this.projectForm.projectDescription
            };
            this.$post('/api/project', param).then(res => {
              this.handleResult(res);
            });

2 后来尝试了下async 和 await,这样是可以成功的

      createProjectTest() {
       let param = {
              projectName: this.projectForm.projectName,
              projectDescription: this.projectForm.projectDescription
            };
       return this.$post('/api/project', param).then(res => {
          return res;
        });
      },
       createProjectConfirm () {
        this.$refs['projectForm'].validate( async (valid) =>{
            if(valid) {
                let res = await this.createProjectTest();
                console.log(res);

                if(res.state !== 0) {
                  this.$message({
                          message: res.message,
                          type: 'warning'
                        });
                } else{
                  this.$message({
                          message: res.message,
                          type: 'success'
                        });
                        this.$refs['projectForm'].resetFields();
                        this.dialogFormVisible = false;
                        this.getProjectList(1);
                }
            }

        })

之前报错await is a reserved word,是因为错把async放到createProjectTest上,这里async和await是成对出现的,所以应该放在匿名函数的位置,加async的函数会被await阻塞,await会跳出async让出线程,所以说学一个东西是一回事,会用一个东西是另外一回事。。自勉下

 

你可能感兴趣的:(vue,es7)