因此,我在created()钩子中进行了一个api调用,但是在api调用完成后,我想在我的应用程序中触发一些事情,但是我不确定该怎么做。平均而言,我的API调用大约需要5秒来返回大量的垃圾数据(我知道这很糟糕)。在下面的示例中,在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解决方案。
如何在vue.js中标识我的示例中的api调用何时完成?
发布于 2019-06-21 05:49:29
你的代码在概念上是好的。问题是
.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'))
发布于 2019-06-21 05:43:54
您需要将函数传递给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
};
})
}
https://stackoverflow.com/questions/56694139
复制相似问题