【问题标题】:Do something after response is finished?响应完成后做些什么?
【发布时间】:2017-01-12 15:42:14
【问题描述】:

我想做的是在响应完成后在数组中添加一些数据。 我试图检查响应是否准备好但没有成功:

this.$http.post('/blog/article/' + articleid + '/comment', article_comments)
.then(function (response) {
    self.comment_id = response.data.comments.id;
    this.user = response.data.comments.user;
    this.dataReady = true;
  }, function (response) {

});

if (this.dataReady == true) {
  this.comments.push({
      comment: this.comment,
      downvotes: 0,
      upvotes: 0,
      user:this.user,
      date_ago: moment(Date.now()).fromNow()
    })
  this.loadComments();
  console.log(this.comments);
}

我该如何解决这个问题?因为我需要来自响应的数据然后推入数组,否则如果我在响应完成之前尝试推入数组会出错。

【问题讨论】:

  • 你可以使用更多的 Promise。如果您返回响应,您可以将.then 与另一个.then(function (response) {...}) 连接起来。它将使用适当的逻辑顺序进行这些异步调用

标签: vuejs2 vue.js


【解决方案1】:

您可以将以下代码放入方法中获取响应后要执行的代码:例如updateOtherVars

if(this.dataReady == true){
        this.comments.push({
            comment: this.comment,
            downvotes: 0,
            upvotes: 0,
            user:this.user,
            date_ago: moment(Date.now()).fromNow()

          })
            this.loadComments();
              console.log(this.comments);
      }

并从this.$http 块中调用此方法,如下所示:

this.$http.post('/blog/article/' + articleid + '/comment', article_comments).then(function(response){
          self.comment_id = response.data.comments.id;
          this.user = response.data.comments.user;
          this.dataReady = true;
          this.updateOtherVars()   //Call method from here
        },function(response){

      });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2013-12-10
    • 2012-08-12
    • 1970-01-01
    相关资源
    最近更新 更多