Sid Scott
Sid Scott

Reputation: 1

How to "order" async methods? Example: Function B relies on Function A resolving first

I'm new to angular/firestore/ionic. I know the following code is bad, but I'm not sure how to improve it. I tried using awaits ... then I tried "callbacks" but couldn't seem to figure it out. I'm not sure if there is an issue with it being specific to typescript, angular 8 or ionic. Sorry if this is a duplicate question but I really need clarification if possible.

I tried following Call multiple async methods that rely on each other but it's in c# and I found Running function with async method in sequential order confusing to be honest.

 constructor(public modalController: ModalController,private crudService: CrudService, public afAuth: AngularFireAuth, private db: AngularFirestore) { 

    setTimeout( () => {this.currentUserID = this.afAuth.auth.currentUser.uid}, 1000)

    setTimeout( () =>{
      var docRef = db.collection('users').doc(this.currentUserID);
      docRef.snapshotChanges().subscribe(data => {
        console.log(data.payload.data()['selectedDate'])
        this.selDate = data.payload.data()['selectedDate']
      })
    }, 2000)

    setTimeout( () =>{
      var docRef = db.collection('users').doc(this.currentUserID);

      docRef.snapshotChanges().subscribe(data => {
        console.log(data.payload.data()['selectedEx'])
        this.selEx = data.payload.data()['selectedEx']
      })
    }, 3000)


  setTimeout(() =>{
    var getSetsRef = db.collection('users').doc(this.currentUserID).collection('dates').doc(this.selDate).collection('userExercises').doc(this.selEx);
    getSetsRef.snapshotChanges().subscribe(data => {
      console.log(data.payload.data()['sets'])
      this.sets = data.payload.data()['sets']
    })
  }, 4000)


}

Upvotes: 0

Views: 79

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317487

It looks like you only need to perform each of these queries once, not set up listeners to their continual changes. If that's the case, you should be using get() to perform a query once instead of snapshotChanges(), which invokes a callback any time the results of the query changes. get() returns a promise, and it should be straightforward to chain them all together or use async/await.

Upvotes: 1

Related Questions