I am writing this code where I am sending a sequence of asynchronous post requests by using a loop. When the callback related with the post request is called I want to use the loop variable which I directly cannot use because of javascript scoping rules. The code is like this:
for(i=0;i<10;i++)
{
$.post(url,requestData,function(data,status,xhr){
// use variable i
}
I cannot directly use i due to scoping rules related to callbacks in javascript. So I want to pass 'i' as a parameter to the callback but the documentation says there can be only 3 parameters associated with this callback. Is there any way to pass additional parameter?
You can use the variable i inside the callback if i is block scoped. Declare i with let keyword
for(let i=0;i<10;i++)
{
$.post(url,requestData,function(data,status,xhr){
// use variable i
}
}
Here's a demo
const $ = {
post: function(callback) {
setTimeout(() => callback(123, 'OK', null), 1000);
}
}
for(let i=0;i<5;i++)
{
$.post(function(data,status,xhr) {
// use variable i
console.log(i);
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With