3

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

I am using setTimeout here to demonstrate an async task (such as your $.post event).

for (i=0; i<10; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

i has changed before you get to run your console.log.

Instead, you must retain a COPY of the i value at the appropriate number.

for (i=0; i<10; i++) {
  const idx = i;
  setTimeout(() => {
    console.log(idx);
  }, 1000);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.