I have the following script, which runs 5 ajax requests and tells when they are done. All that using jQuery promises and $.where
.
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?