首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在vue.js中识别何时完成获取

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

Stack Overflow用户
提问于 2019-06-21 05:30:49
回答 2查看 642关注 0票数 0

因此,我在created()钩子中进行了一个api调用,但是在api调用完成后,我想在我的应用程序中触发一些事情,但是我不确定该怎么做。平均而言,我的API调用大约需要5秒来返回大量的垃圾数据(我知道这很糟糕)。在下面的示例中,在api调用完成之前就打印了日志语句。

来自组件的代码片段:

代码语言:javascript
运行
复制
<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()钩子中,但也不起作用。

我相信我可以使用以下命令来实现我想要的:

代码语言:javascript
运行
复制
  $(window).on('load', function(){
    console.log('this logs after the entire page loads')
    });

但我相信有一种更优雅的vue.js解决方案。

如何在vue.js中标识我的示例中的api调用何时完成?

EN

回答 2

Stack Overflow用户

发布于 2019-06-21 05:49:29

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

代码语言:javascript
运行
复制
.then(console.log('print AFTER the api call is completed'))

尽管promise.then调用注册了异步处理程序,但调用本身是同步计算的,它们只是将异步回调函数作为参数。当你调用

代码语言:javascript
运行
复制
.then(console.log('print AFTER the api call is completed'))

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

相反,在这里传入一个函数,您应该会看到日志在适当的时间到来:

代码语言:javascript
运行
复制
.then(() => console.log('print AFTER the api call is completed'))
票数 1
EN

Stack Overflow用户

发布于 2019-06-21 05:43:54

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

代码语言:javascript
运行
复制
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
      };
    })
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56694139

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档