Synchronizing http.post request

Hi all,

I am new to Angular 2. I have an issue which I can’t find the solution.
I am trying to develop a system which parses a file and send line by line (after parsing as json) to server.
I have a loop which runs on the file and place a http.post request per line.
In case of success, a second http.post to a different api is done.
In case of failure of the first call, i want to print the error and the line in the file caused the error.
The problem is that since this is a asynch call, i can’t make the second http.post because the response return only after all calls are done. When trying to get the row of the error, I get the last row in the file. snip code:

for (var row = 0; row < rows.length; row++) {
    let strBody = JSON.stringify(row);
    res = this.http.post(url1, strBody, options)
    if(success) {
        strBody = JSON.stringify(res);
        this.http.post(url2, strBody, options)       
        if(fail) {
            //add error to table in html including row and strBody + reason
            //the problem is when reaching this location row = rows.length 
        }
    } else {
        //add error to table in html including row and strBody + reason
        //the problem is when reaching this location row = rows.length 
    }
}

I understand that the reason is the async nature of the call.
I appreciate your help

Not exactly sure where the success and fail are being generated, so it’s a bit tough to offer the exact example you probably need, but check out this article: https://blog.lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795

It should offer you some insight into how to run a sequenced loop of awaited tasks.

1 Like

Is this a Meteor question? Your code suggests it’s not. You may get a better response on SO.