THEN ARRAY EMPTY PROMISSE [duplicate]

2019-09-27 16:24发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 36 answers
  • Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference 6 answers

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

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.

回答1:

You can use async and await.

In service.

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);
      })
  }

In component,

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