【问题标题】:Can not use keyword 'await' outside an async function in VUEJS不能在 VUEJS 中的异步函数之外使用关键字“等待”
【发布时间】:2020-07-11 08:25:26
【问题描述】:

当我尝试在异步函数Can not use keyword 'await' outside an async function 之外等待时遇到此错误,我想知道我应该使用哪种方法来解决此问题?提前致谢。

这是我的代码:

async addCoursToClassYear() {
  setTimeout(() => {
    this.loading = false;
    await this.$store.dispatch("academicYear/addCoursToClassYear", {
        ...this.form,
        ...this.singleYear
      })
      .then(() => {
        this.handleSuccess();
        this.closeModal();
      })
      .catch(error => {
        if (error.response.status === 422) {
          this.serverValidation.setMessages(error.response.data.errors);
        } else {
          this.handleError(error);
        }
      });
  })
},

【问题讨论】:

  • setTimeout(async () => { - 应该可以解决它。
  • 为什么要毫不拖延地setTimeout?它会将回调放置在事件队列中,是的,但是如果回调已经是异步的,那么将其调用至少延迟 4 毫秒有什么意义?
  • @DrewReese,我忘了添加延迟。但我设置setTimout 的原因是因为我希望在提交请求之前加载提交按钮并禁用 2 秒。避免用户双击。
  • 我认为您可以删除 dispatch 前面的等待。看起来没有理由在函数中使用 async/await。

标签: javascript reactjs vue.js


【解决方案1】:

您在 setTimeout 中使用 await。所以,你需要做一个异步 setTimeout 函数

async addCoursToClassYear() {
  setTimeout(async() => {
    this.loading = false;
    await this.$store.dispatch("academicYear/addCoursToClassYear", {
        ...this.form,
        ...this.singleYear
      })
      .then(() => {
        this.handleSuccess();
        this.closeModal();
      })
      .catch(error => {
        if (error.response.status === 422) {
          this.serverValidation.setMessages(error.response.data.errors);
        } else {
          this.handleError(error);
        }
      });
  })
},

我变了

setTimeout(() => {

setTimeout(async() => {

【讨论】:

    【解决方案2】:

    在这里,将 async 放在您使用 await 的函数中。

    async addCoursToClassYear() {
      setTimeout(async () => {
        this.loading = false;
        await this.$store.dispatch("academicYear/addCoursToClassYear", {
            ...this.form,
            ...this.singleYear
          })
          .then(() => {
            this.handleSuccess();
            this.closeModal();
          })
          .catch(error => {
            if (error.response.status === 422) {
              this.serverValidation.setMessages(error.response.data.errors);
            } else {
              this.handleError(error);
            }
          });
      })
    },
    

    【讨论】:

    • 记住有一个副作用,我希望你已经知道异步的副作用,promise 解决的事情。 :)
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 2020-04-15
    • 2020-02-17
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多