0

I use $.when to call an ajax function in a loop:

for ( var i = 0; i < 4; i++ ){
    $.when(get_total_price("var1","var2")).then(function (v) {
        console.log("i= "+i);
    });
}

I expect that in every iteration, it waits for the ajax call to be completed, than the next iteration is executed, so the result of this simple example will be:

i= 1
i= 2
i= 3

but the result is:

i= 5
i= 5
i= 5

In this case I can't use the i inside the ajax call!

Aminesrine
  • 2,082
  • 6
  • 35
  • 64

2 Answers2

3

The function callback is done asynchronously and thus called after the loop terminates.

ftyross
  • 31
  • 1
1

As others have pointed out, when is the deferred model of doing async programming in javascript. The loop terminates before the async functions, i.e. when callbacks, are called. Here is a hack to make it work by using IIFE:

for ( var i = 0; i < 4; i++ ){
    (function() {
        $.when(get_total_price("var1","var2")).then(function (v) {
            console.log("i= "+i);
        })
    )(i);
}
Lim H.
  • 9,870
  • 9
  • 48
  • 74