Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda