0

I have the following script, which runs 5 ajax requests and tells when they are done. All that using jQuery promises and $.where.

http://jsfiddle.net/r269j65r/

console.info('Creating promises: start');
var p = [];
for(var i=0; i<5; i++) {
    a = $.when( x(i) ).done(function(){
        console.log('Promise ' + i + ': done');
    });
    p.push(a);
}
console.info('Creating promises: done');
console.log('Running promises: start');

$.when.apply($,p).done(function(){
    console.log('Running promises: done');
});

function x(i) {
    console.log('Promise ' + i + ': start');
    return $.ajax({
        'url' : '/'         
    })
    .done( function() {
    });
}

The problem is that console.log('Promise ' + i + ': done'); always returns Promise 5: done, because i-variable has value 5 when the done() function is executed.

My question is what be a good and clean way to give i to the context of the done()-function in the for-loop?

Jacob
  • 2,769
  • 3
  • 21
  • 29
ddofborg
  • 2,028
  • 5
  • 21
  • 34

1 Answers1

3

You need to use closure to make this work (Closures on MDN)

A working fragment:

for(var i=0; i<5; i++) {
    (function(i){
        a = $.when( x(i) ).done(function(){
            console.log('Promise ' + i + ': done');
        });
        p.push(a);
    })(i);
}

And the full fiddle...

Amit
  • 45,440
  • 9
  • 78
  • 110