Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda