【问题标题】:How to run a fallback upon multiple Axios calls?如何在多个 Axios 调用上运行回退?
【发布时间】:2019-03-29 17:47:39
【问题描述】:

在我的应用程序中,评论可以是父级并有子级 cmets。删除父评论时,我正在检查孩子是否存在;如果是这样,我也会删除它们(每个都有一个单独的 Axios 调用)。

但是一旦完成所有这些,我需要运行一些刷新代码。有没有一种简单的方法来实现这一点?我可以在哪里放置刷新代码?

到目前为止,这是我的代码:

deleteCommentAxiosCall (id) {
  return this.$axios.delete(`/api/v1/comment/${this.comment.id}`)
},
deleteComment () {
  return new Promise((resolve, reject) => {
    this.deleteCommentAxiosCall(this.comment.id)
    if (this.comment.child_comments.length) {
      this.comment.child_comments.forEach((child) => {
        this.deleteCommentAxiosCall(child.id)
      })
    }
  })
  window.location.reload() // refresh code

【问题讨论】:

    标签: javascript vue.js vuejs2 axios


    【解决方案1】:

    您必须链接承诺以确保在刷新之前解决删除问题。使用Promise.all() 一次等待多个承诺。在这种情况下,您将等待删除父评论以及子 cmets。

    deleteComment () {
      return Promise.all([
        this.deleteCommentAxiosCall(this.comment.id),
        this.comment.child_comments.map(child => this.deleteCommentAxiosCall(child.id))
      ])
      .then(() => window.location.reload())
    }
    

    或者使用async function:

    async deleteComment () {
      await Promise.all([
        this.deleteCommentAxiosCall(this.comment.id),
        this.comment.child_comments.map(child => this.deleteCommentAxiosCall(child.id))
      ])
      window.location.reload()
    }
    

    另外:重新加载页面可能会让用户感到有些不适。也许刷新 cmets 的更无缝方式是通过显式 API 请求重新请求 cmets。示例:

    this.$axios.get(`/api/v1/comments`).then(resp => this.comments = resp.data.comments)
    

    【讨论】:

    • 再次感谢您的正确答案和第二个建议,这实际上非常好!
    • @drake035 没问题 :)
    猜你喜欢
    • 1970-01-01
    • 2020-02-13
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多