user8090896
user8090896

Reputation:

why is index getting incremented like this? javascript

First console log: 0, as expected. Second console log: 1. Why index got incremented before the end of loop?

for (var i = 0; i < this.offlineTimeSlots.length; i++) {

          console.log(i);

          this.http.post('http://localhost:63203/api', JSON.stringify(this.offlineTimeSlots[i]), { headers: headers })
            .map(res => res.json())
            .subscribe(data => { 

              console.log(i);

              resolve(data);
            }, (err) => {
              reject(err);
            });
        }

Upvotes: 0

Views: 58

Answers (2)

eko
eko

Reputation: 40647

When you make an operation inside the for loop like that basically you are generating this.offlineTimeSlots.length of http requests (async). Depending on the length of the loop, usually the for loop will complete its loop almost everytime before the http request.

Take a look at this example:

for(var i = 0; i < 10; i++){
    console.log(i);
    setTimeout(()=>{
        console.log(i);
    },2000);
}

This will print the numbers from 0 to 10 (10 excluded) and then print 10, ten times. The reason is you are creating 10 (length of the loop) async requests while looping. And since the for loop will finish the traversal quicker than 2 seconds, i will be 9 + 1 (post incrementation) by the time setTimeouts start.

Source fiddle: https://jsfiddle.net/echonax/c9p4e19o/

Upvotes: 1

Vivek Doshi
Vivek Doshi

Reputation: 58533

this.http.post is the asynchronous function so it will executed separately

For loop will continue its execution and it's not depends on the this.http.post.

Concept is called event-loop : Please read this

Upvotes: 0

Related Questions