Skip to content
Advertisement

async and await in angular api response

I am trying to do task step by step.

I have a for loop in a method:

async changeTimeStep3() {
  for (let i = 1; i < 10; i++) {
    await this.do(i)
  }
}

for each step must do() task.

do(i) {
  this.http
    .getDataFromServer(
      "api/example?id=" +i
    )
    .subscribe((response) => {
     console.log(i);
    });
}

  

I want to wait to get response and after response coming go to next i

But not work console.log print:

2
3
5
1
4
7
8
9
6

Note time to receive response from api is not fix.

Any help?

Advertisement

Answer

You can return a Promise and use resolve() in response part of your ajax. Like:

do(i) {
  return new Promise((resolve, reject) => {
    this.http.getDataFromServer("api/example?id=" +i).subscribe((response) => {
      resolve(response);
    }, (error) => {
      console.error(error);
      reject();
    });
  });
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement