Issue
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?
Solution
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();
});
});
}
Answered By - Mahdi Zarei
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.