Satya Ram
Satya Ram

Reputation: 109

Make Synchronus Api inside for Loop

I have an array of Objects/String.

this.addtenant().subscribe(r => {
    let a = ['plant1', 'plant2'];
    for (let b of a) {
        this.myService.saveAllData(b).subscribe(r => {
            console.log("result" r);
        });
    }
});

and getAllData is in myservice file which returns an Observable.

    saveAlldata(b) {
     this.http.post(url,b);
    }

The problem is since i am using subscribe the call is being asynchronus, i want to have it something like: first "plant1" post call has to finish, and then plant2 has to be made. In simple words synchronus call.

Upvotes: 0

Views: 58

Answers (2)

Satya Ram
Satya Ram

Reputation: 109

I have found a solution by myself. You can use an async await inside a loop, since forEach is not promise aware and cannot be used with Promise. Here is the final code:

this.addtenant().subscribe(async r => {
let a = ['plant1', 'plant2'];
for(let index=0; index=a.length; index++)
    await this.myService.saveAllData(b).toPromise().then(r => {
        console.log("result" r);
    });
}
}
});

As await works with Promise, so toPromise will replace subscribe()

Upvotes: 0

AhmerMH
AhmerMH

Reputation: 688

I think you should use async/await for synchronous calls.

Here is one of the tutorial: https://www.techiediaries.com/javascript-async-await-tutorial/

A sample code demo would be something like:


responseArr: any[] = [];

func1()
  let x = [1,2,3];
  func2(x);
}

async func2(arr) { // make the function async
  for(let i=0; i<arr.length ; i++){
    const response: any = await this.myService(arr[i]); // wait on each service call. This will give synchronous behaviour
    this.handleResponse(response); // handle response in a function if there is common functionality in each response
  }
  reuturn responseArr; // return the final response
}

handleResponse(response) {
  responseArr.push(response);
}

Upvotes: 1

Related Questions