I am trying to do task step by step.
I have a for loop in a method:
JavaScript
x
6
1
async changeTimeStep3() {
2
for (let i = 1; i < 10; i++) {
3
await this.do(i)
4
}
5
}
6
for each step must do() task.
JavaScript
1
12
12
1
do(i) {
2
this.http
3
.getDataFromServer(
4
"api/example?id=" +i
5
)
6
.subscribe((response) => {
7
console.log(i);
8
});
9
}
10
11
12
I want to wait to get response and after response coming go to next i
But not work console.log print:
JavaScript
1
10
10
1
2
2
3
3
5
4
1
5
4
6
7
7
8
8
9
9
6
10
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:
JavaScript
1
11
11
1
do(i) {
2
return new Promise((resolve, reject) => {
3
this.http.getDataFromServer("api/example?id=" +i).subscribe((response) => {
4
resolve(response);
5
}, (error) => {
6
console.error(error);
7
reject();
8
});
9
});
10
}
11