Run the promises in order (not in parallel)

Hi,
I have an array of favoris id and for all off them I make a request to get all the infos.
It’s working, but as the calls are async, in the end, the listing is in random order.

Is there a way to keep the responses in the same order as the call and to chain my promises ?

I also saw that is possible with http request with .flatMap() but I dont know how to use it in my case :frowning:

Here my code for now :

 ionViewWillEnter(){

      this.allFavoris = [];
      this.listFavoris = [];
      let totalPromise=[];
          this.local.get('mlvi_favoris').then(allFavorisStr => {         
              this.allFavoris = JSON.parse(allFavorisStr);  
              if(this.allFavoris.length>0){
                  for(let i = 0; i < this.allFavoris.length; i++) {
                    this.recupInfoStation(this.allFavoris[i]).then(data => {        
                        this.listFavoris.push(data);
                    });                
                  }
              }
          });      

    }


        recupInfoStation(id){
         return new Promise((resolve) => {
                this.http.get(url).map(res => res.json()).subscribe(
                    data => {
                        resolve(data);
                    });
                 });
         }

Thanks for your help !

When I want to execute one promise after the other aka chain promises, I do something like that:

let promises = new Array();
promises.push(getYourPromise1());
promises.push(getYourPromise2());
etc.

and then to run these promises in order:

Observable.forkJoin(promises).subscribe((data:any) => {
    console.log('awesome');
},
(err:any) => {
    console.error('damned');
});

P.S.: getYourPromise1() could be declared like following for example

getYourPromise1():Promise<{}> {
 return new Promise((resolve, reject) => {
   resolve();
 }, {
   reject();
 });
}

P.P.S.: There is probably a better solution, I’m not against learning about it

Think you @reedrichards for taking the time to answer me, but same result with forkJoin as it seems it runs the promises in parallel too :slight_frown:

You are right, forkJoin run the promises in parallel and wait for all promises to be complete. But aren’t the results delivered in the same order as they are provided to forkJoin?

Like

 Rx.Observable.forkJoin([a,b]).subscribe(t=> {
    var firstResult = t[0]; // -> see below
    var secondResult = t[1];
});

here -> Is that the result of promise “a” or could that be also the result of “b”, if “b” was quicker than “a”? If “no it’s always a”, then you will have your results in the order you specified…again not sure about it

1 Like

Seems working with your last code !! Many thanks for your help !! :+1:

Here my final code :

 ionViewWillEnter(){

     this.allFavoris = [];
     this.listFavoris = null;
     let totalPromise = [];

      this.local.get('mlvi_favoris').then(allFavorisStr => {             
          this.allFavoris = JSON.parse(allFavorisStr);
          if(this.allFavoris.length>0){
              for(let i = 0; i < this.allFavoris.length; i++) {
               totalPromise.push(this.recupInfoStation(this.allFavoris[i])) ;                
              }
          }

          Observable.forkJoin(totalPromise).subscribe(t => {    
            this.listFavoris = t;
          },
           (err:any) => {
            console.error('damned');
          });
      });
      

}


recupInfoStation(id){
 return new Promise((resolve) => {
        this.http.get(url).map(res => res.json()).subscribe(
            data => {
                resolve(data);
            },error=>{
                console.log('NOOOOOO!');
            });

         });
 }
1 Like

Awesome! I also learned something, thx you too :slight_smile: