如何对多个Axios调用进行回退?

时间:2019-03-29 17:47:40

标签: javascript vue.js vuejs2 axios

在我的应用中,评论可以是父评论,也可以是子评论。删除家长评论时,我正在检查孩子是否存在;如果是这样,我也要删除它们(每个都有一个单独的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

1 个答案:

答案 0 :(得分:2)

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

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

也:重新加载页面可能会对用户造成一定的影响。刷新注释的一种更无缝的方法可能是通过显式API请求重新请求注释。示例:

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