ChristoK ChristoK -4 years ago 39
Javascript Question

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);
});
}

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download