然后阵列清空承诺 [英] THEN ARRAY EMPTY PROMISSE

查看:33
本文介绍了然后阵列清空承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个方法来通过调用promise来在Firestore中获取时间,但是该数组为空,因为尚未解决诺言.如何解决只有在getTime()调用终止时才能调用数组的方法.

Create a method to fetch time in the firestore by calling the promise, but the array comes empty because the promise has not yet been resolved. How to resolve to call the array only when a getTime () call terminates.

Angular Cli 8

Angular Cli 8

example.service.ts

teste: [];

getTime() {
    this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('Não existem marcacoes até o momento por favor aguarde')
        } else {
          res.forEach(ponto => {
            console.log(ponto.id);
            console.log(ponto.data().time.seconds * 1000);
            this.time.push(new Date((ponto.data().time.seconds * 1000)));
          })
        }
      }).catch(err => {
        console.log(err);
      })
  }

example.component.ts

ngOnInit() {
    this.mainService.getTime();
    console.log(this.mainService.time);
  }

我希望在调用该数组变量时已经完成.

I hope the array variable is already complete when I call it.

推荐答案

您可以使用 async await .

在使用中.

getTime() {
    return this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('Não existem marcacoes até o momento por favor aguarde')
        } else {
          res.forEach(ponto => {
            console.log(ponto.id);
            console.log(ponto.data().time.seconds * 1000);
            this.time.push(new Date((ponto.data().time.seconds * 1000)));
          })
        }
        return true;
      }).catch(err => {
        console.log(err);
      })
  }

在组件中,

async ngOnInit() {
    await this.mainService.getTime();
    console.log(this.mainService.time);
}

这篇关于然后阵列清空承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆