-2

in this piece of code the subscribe function executes after the last line in loadFromDB function:

  loadFromDB(){
    const loading = this.loadingCtrl.create({
      content: 'pleas wait'
    });
    loading.present();
    this.getInterviewFromDB()
      .subscribe((data) => {
        this.events = data;
        console.log( 'before');
      });
    this.getMeetingsFromDB().subscribe((data)=>{
      this.events.concat(data);
    });
    loading.dismiss();

    console.log( 'after');
  }

the loading is present and dismiss before loading any data from database and this is the output of the log

enter image description here illustrates that line under the subscribe function Execute after the console.log inside it ...can any body explain to me .. ?!

Andrei Matracaru
  • 3,511
  • 1
  • 25
  • 29
Tawfiek Khalaf
  • 497
  • 4
  • 18
  • 1
    It is a common problem that developers encounter with JavaScript. So you are in familiar territory. Check out https://stackoverflow.com/questions/14382567 and https://stackoverflow.com/questions/2637626 – James Lawruk Aug 24 '17 at 17:18

2 Answers2

1

This makes perfectly sense. You are subscribing to asynchronous steams. You cant expect them to finish in order. If you want them to finish at the same time you can do something like this:

Observable.forkJoin(this.getInterviewFromDB(), this.getMeetingsFromDB())
    .subscribe(res => {
       let interviews = res[0];
       let meetings = res[1];
    })
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
0

This is the way callbacks work. subscribe takes a callback function as an argument. I suggest you learn what callbacks are and how they work before continuing.

Here is a little bit of information on how subscribe works: ReactiveX subscribe function

Robin provides a good solution in his answer with forkJoin. forkJoin joins the values emitted by multiple Observables into an array and creates a new Observable. You can then subscribe to this Observable, just like Robin did in his example, to get the array value which is the first argument of the callback.