如何在vue.js中识别何时完成提取

时间:2019-06-20 21:30:48

标签: javascript vue.js

因此,我在我的created()挂钩中进行了api调用,但是我的应用程序中有一些事情要在api调用完成后触发,但是我不确定该怎么做。平均而言,我的API调用大约需要5秒才能返回大量的json(我知道这很糟糕)。在下面的示例中,在api调用完成之前,日志记录语句打印良好。

来自组件的代码段

<script>
  created() {
    this.myEndpoint = 'testserver.com'
    fetch(this.myEndpoint)
    .then(response => response.json())
    .then(body => {
      for(let i=0; i<body.length; i++){
        this.job_execs.push({
          'version': body[i].version,
          'platform': body[i].platform.name,

        })
      }
    })
    .then(console.log('print AFTER the api call is completed'))
    .catch( err => {
      console.log('Error Fetching:', this.myEndpoint, err);
      return { 'failure': this.myEndpoint, 'reason': err };
    })
  },
};
</script>

我尝试将console.log语句移到Mounted()钩上,但这也不起作用。

我相信我可以实现我想要的:

  $(window).on('load', function(){
    console.log('this logs after the entire page loads')
    });

但是我敢肯定还有一个更优雅的vue.js解决方案。

示例中的api调用完成后,如何在vue.js中识别

2 个答案:

答案 0 :(得分:1)

您的代码概念上不错。 问题是

.then(console.log('print AFTER the api call is completed'))

即使promise.then调用注册了异步处理程序,这些调用本身也是被同步评估的,它们只是应该将异步回调函数作为参数。通话时

.then(console.log('print AFTER the api call is completed'))

console.log('print AFTER the api call is completed')被同步评估(注销消息),然后将其返回值(undefined)作为回调传递给.then

在此处传递函数,您应该会在适当的时间看到日志:

.then(() => console.log('print AFTER the api call is completed'))

答案 1 :(得分:0)

您需要将函数传递给then语句。您拥有的将执行console.log并将其结果传递给then语句(即undefined/void)。

created() {
  this.myEndpoint = 'testserver.com'
  fetch(this.myEndpoint)
    .then(response => response.json())
    .then(body => {
      for (let i = 0; i < body.length; i++) {
        this.job_execs.push({
          'version': body[i].version,
          'platform': body[i].platform.name
        })
      }
    })
    .then(() => console.log('print AFTER the api call is completed'))
    .catch(err => {
      console.log('Error Fetching:', this.myEndpoint, err);
      return {
        'failure': this.myEndpoint,
        'reason': err
      };
    })
}