0

I am calling a function onRoute() which returns Promise. function will sync my data to API multiple times according to the length of data and returns back with a string message every time. I wanna store it but the problem is for loop gets completed before getting message from API server.

please help me out.

 syncOnRoute() {
    return new Promise((resolve, reject) => {
      this.auth.database.executeSql('select * from onroute where HaveData=?', 
        ['yes']).then((res) => { //will get 3 data from Database
       
        for (let i = 0; i < res.rows.length; i++) { // will execute 3 times
                        
                let params = new HttpParams()
                  .set('CLAIMGUID', res.rows.item(i)['CLAIMGUID'])
                  .set('JOBGUID', res.rows.item(i)['JOBGUID'])
                  .set('Latitude', res.rows.item(i)['Latitude'])
                  .set('Longitude', res.rows.item(i)['Longitude'])
                  .set('OnRouteDT', res.rows.item(i)['OnRouteDT'])
                  .set('Desc', this.auth.getdateformatV2())
                  .set('title', 'onroute');
                  this.auth.httpSend('Service_SaveOnRoute', params, 'post').subscribe((msg) => {
                    console.log('##SUCCESS ONROUTE SYNC' + JSON.stringify(msg)); // getting return msg from API

                  }, 
                  (err) => {
                    console.log('##SUCCESS ONROUTE SYNC' + JSON.stringify(err));
                     
                  }
                );
} // for loop gets completed before geting return msg from API
                
                   
x

Here is my httpSent() which is observable

public httpSend(endPoint:string, params:HttpParams , method: string){
    
    switch(method){

      case 'post':{
        return  this.httpClient.post<any>("https://ws-v3test.ventureprise.cloud/Service1.asmx/"+endPoint,params);

      }
      break;
      case 'get':{
        return  this.httpClient.get<any>("https://ws-v3test.ventureprise.cloud/Service1.asmx/"+endPoint);

      }
    }
  }
Md Danish
  • 1
  • 1

1 Answers1

0

I guess you can change your subscribe to toPromise and use for...of with await

Alternative you can put all this.auth.httpSend('Service_SaveOnRoute', params, 'post') to an array and after loop is end you can wait for all subscribe

I hope it helps you! Enjoy programming!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

  • One way how you can wait for observables completed) https://stackoverflow.com/questions/41734921/rxjs-wait-for-all-observables-in-an-array-to-complete-or-error – Aleksey Zikrackiy Oct 04 '21 at 23:26
  • thank you Aleksey. the problem is resolved now. have used an array to store all the subscribed value. and then will check how many time data send is equals to how many time i recived msg. after check if its true then it will resolve the promise – Md Danish Oct 07 '21 at 20:46