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

148
Views
Let async ajax with loop finish before further codes get run
getUsers();

function getUsers(){
    console.log('Start');

    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/users',
        method: 'GET',
        dataType: 'json',
        success: function (data) {
                data.forEach(user => {
                    console.log(user.id);
                 });                    
        },
        error: function () {
            console.log(data.status);
        }
        
    })

    console.log('End');    
}

The above code-example should print the following: Start ids ... End

However it has the following problem: The order of printing of the data is wrong. It prints Start End data-object

I know it has to do with async, however I can't fix the problem. I tryed alot of things like $.When() Promise async/await But none of them helped.

So could you please show how to fix this problem?

Thank you in advance

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

0

Ajax is asynchronous, the successor the error function will be called later, when the server answer the client. That is why sometimes you can see data.status displayed before End in your last console.log statement. Second, data that you are getting from response does not contain field success. Success callback function gets passed three arguments: The data returned from the server, formatted according to the dataTypeparameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHTobject. In your code you are just passing first argument to it which is data returned from server.

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!