How to deal with this asynchronous programming loop?


#1

I’ve been having problems understanding how asynchronous programming works, I’ve read in the web about it and how to deal with it, but sincerely I’m not understanding how to apply the techniques in my case. I’m using firebase and ionic for making a 1st query and then for every snapshot I get I’m building a non observable object with only the information I’m needing. But since this is asynchronous programming, my logic isn’t working, and the object is only saving repeated information.

My code is:

ionViewWillLoad(){
this.afAuth.authState.take(1).subscribe(data =>{
this.tutores = this.afDatabase.object(`asignaturas/${this.asignatura}`, {preserveSnapshot: true});
this.tutores.subscribe(snapshots => {
    snapshots.forEach(snapshot=>{
      console.log(snapshot.key);
      var padre=snapshot.key;
      this.consultaTutor=this.afDatabase.object(`profile/${snapshot.key}`, {preserveSnapshot: true});
      this.consultaTutor.subscribe(info=>{
        info.forEach(childSnapshot=>{
          var value=childSnapshot.val();
          var key = childSnapshot.key;
          this.infoTutores[key]=value;
        })
        this.listaTutores.push(this.infoTutores);
        console.log(this.listaTutores);
      })

      //this.afDatabase.object(`profile/${snapshot.key}`);
    })
});

})

}

This is my data structure in firebase:

And this is the output for the array it builds:

The info is repeated because when I’m gonna loop the information on profile I subscribe to that, and the program does not go into the next function. Instead it keeps looping until it finishes the first loop (the object SIHGkc…), and only does the inner loop with that object.

Any suggestions on how to deal with it?


#2

most like likely these are return promises
you would need to add .then() structure after

  editMedicationQty(editObj: Medications,idx,ev) {
    ev.stopPropagation().then(result => {

 //then use the result as your data to go into next then

});