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

Javascript 如何在vue.js中识别提取何时完成,javascript,vue.js,Javascript,Vue.js,因此,我在created()hook中进行了一个api调用,但在我的应用程序中,有一些事情我想在api调用完成后触发,但我不确定如何做到这一点。平均来说,我的API调用需要大约5秒钟才能返回一大块json(我知道这很糟糕)。在下面的示例中,日志语句在api调用完成之前就打印出来了 来自组件的代码段: <script> created() { this.myEndpoint = 'testserver.com' fetch(this.myEndpoint)

因此,我在created()hook中进行了一个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>
但我相信有一个更优雅的vue.js解决方案


当我的示例中的api调用完成时,如何在vue.js中进行标识

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

created(){
this.myEndpoint='testserver.com'
获取(this.myEndpoint)
.then(response=>response.json())
。然后(body=>{
for(设i=0;iconsole.log('api调用完成后打印'))
.catch(错误=>{
log('Error Fetching:',this.myEndpoint,err);
返回{
“失败”:this.myEndpoint,
“原因”:错误
};
})
}

您的代码在概念上很好。 问题是

.then(console.log('print AFTER the api call is completed'))
即使
promise.then
调用注册异步处理程序,调用本身也是同步计算的,它们只是应该将异步回调函数作为参数。当你打电话的时候

.then(console.log('print AFTER the api call is completed'))
console.log(“api调用完成后打印”)
将同步计算(注销消息),然后将其返回值(
undefined
)传递给
。然后作为回调

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

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

在这个函数中:
。然后(body=>{/*您的for循环*/console.log('API Finished')})
感谢这项工作——并且将作为临时解决方案工作,但我希望vue中内置了某种东西,可以确定页面是否已加载或所有组件都已加载。我相信在我当前的项目中,vue认为该组件已加载,尽管API调用耗时5秒。因此,例如,如果我想实现加载动画,我不确定要挂接什么以确保页面正在加载。您可以在这里执行
。然后(()=>console.log('print AFTER the api call is complete'))
但是前面的
然后(body…
需要返回一个承诺,例如
return promise.resolve()
@GetOffMyLawn
那么
调用如果是同步的,则不需要返回承诺。特别是,从
然后
调用返回
承诺.resolve()
总是多余的。我在这里提供此澄清,因为我看到您已经修改了您的问题
.then(console.log('print AFTER the api call is completed'))
.then(() => console.log('print AFTER the api call is completed'))