【问题标题】:How to switch from .then to async await in Vue JS如何在 Vue JS 中从 .then 切换到异步等待
【发布时间】:2022-02-11 14:58:10
【问题描述】:

我想知道如何将已经通过.then异步的created函数切换到async await

created() {
    this.$http.get("wp/v2/posts").then(
      response => {
        for (let post in response.data) {
          this.posts.push(response.data[post]);
        }
        this.$store.dispatch({
          type: "updatePost",
          value: this.posts
        });
      },
      error => {
        alert(error);
      }
    );
}

我可以轻松地添加async created() 并等待this.$http.get,但无法弄清楚error => {} 部分,因为responses 的花括号也将消失。

【问题讨论】:

  • 您切换的任何具体原因?它们都是相似的,并且动作相同(几乎)。我想知道你为什么选择切换。
  • 对于await,你应该使用try/catch
  • @AlwaysHelping 嘿,我没有切换的具体原因,只是为了锻炼和好奇。
  • 我明白了。很公平。如上所述,您也可以使用此处解释的 try/catch 块来执行此操作并处理错误:stackoverflow.com/questions/40884153/…
  • 好吧,让我尝试在下面发布答案。谢谢大家的建议

标签: vue.js async-await


【解决方案1】:

感谢有关 try and catch 的建议。如果我错了,请纠正我:

async created() {
    const response = await this.$http.get("wp/v2/posts")
    
    try {
      for (let post in response.data) {
        this.posts.push(response.data[post]);
      }
      this.$store.dispatch({
        type: "updatePost",
        value: this.posts
      });
    }
    catch (error) {
      alert(error);
    }
}

【讨论】:

  • 您忘记了链式调度承诺。这在这里影响不大,因为 Vuex 应该抑制错误 iirc,但无论如何,这是正确的做法
  • 嗨@EstusFlask,请问您在这种情况下如何发送承诺?
【解决方案2】:

我认为你可以使用这个而不是使用 try:

async created() {
  await this.$http.get("wp/v2/posts").then(response => {
    for (let post in response.data) {
      this.posts.push(response.data[post]);
    }
    this.$store.dispatch({
      type: "updatePost",
      value: this.posts
    });
  }).catch(function () {
    alert(error);
  })
}

【讨论】:

  • 我认为我们应该只使用 async 和 await 或者 .then?而不是同时
  • 我在我的项目中使用了这样的 await-catch 结构,它可以工作。在您的项目中测试答案以确保确定!
  • async/await 应该完全取代原始的 Promise (then/catch),特别是因为它们会导致更复杂的代码,容易出错。在这里你还是忘了链 dispatch promise。
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2021-10-22
  • 2021-02-07
  • 2018-06-11
  • 1970-01-01
相关资源
最近更新 更多