Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

187
Views
for is adding i++ before performing an entire action, ajax async

The problem is the following, I have an array, I perform a for that traverses this array and for each element inside the array it performs an AJAX request, and even though I put the async: false property, apparently it is still an asynchronous request, which does so that the variable i inside the for loops through everything and only performs the request on the last element of the array.

    for(let i = 0; i < array.length; i++){
        let elemnt = array[i]
        console.log(i)
        $.ajax({
            async: false,
            url: 'https://xxx.xxxxxxxxxx.xxx.xx/'+elemnt,
            type: 'GET',
            success: (data)=>{
                //does something with array element...                   
                }
            })
        }

putting the console.log(i) was then to output:

    0
    *Perform AJAX request with array[0]*
    1
    *Perform AJAX request with array[1]*
    2
    *Perform AJAX request with array[2]*

however it stays:

    0
    1
    2
    *Perform AJAX request with array[2]*

I believe this is all due to Ajax's Asynchronous realization, but I already put async: false, I don't know what else it could be.

Thanks in advance for anyone who can help.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Instead of looping through the array and running ajax in the loop, create a function that ONLY continues when ajax is successful.

In the below example, cur is the position in the array to grab the value from. For the ajax call, I shortened it just for my answer obviously you will need to use your full ajax.

let cur = 0;

function runAjax() {
  $.ajax({
    ......
    success: (data) => {
      if (cur == array.length) {
        console.log("Done!");
      } else {
        cur++;
        runAjax();
      }
    }
  });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!