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

130
Vistas
Ajax Request Answer is slower than code, ajax request after code is processed

I've got the ajax request is very slow so my stats array does not get updated at the second time i want to access it. It seems like the ajax request gets executed after all the code is processed. Is there a way how i can wait for the ajax request to be executed before all the rest of my code?

console.log(stats);
fetchREST(false, (url+selectedID+"/solve"), (parseInt(button.id)+1), function(data){
 if (data.success) {
  console.log("richtig");
  stats.right++;
 } else {
  console.log("falsch");
  stats.wrong++;
 }
});
console.log(stats);

function fetchREST(isGET, path, answer, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };

    let email = "*";
    let pw = "*";

    if(isGET) {
        // not needed
    } else {
        let solutionArray = '[' +  answer +  ']';
        console.log(solutionArray);
        httpRequest.open('POST', path, true);
        httpRequest.setRequestHeader("Content-Type", "application/json");
        httpRequest.setRequestHeader("Access-Control-Allow-Origin", "*"); 
        httpRequest.setRequestHeader("Access-Control-Allow-Headers", "*");
        httpRequest.setRequestHeader("Authorization", "Basic " + window.btoa(email + ":" + pw));
        httpRequest.send(solutionArray);
    }
}

EDIT I fixed it by changing

httpRequest.open('POST', path, true);

to

httpRequest.open('POST', path, false);

Now the async is set to false and the send methods waits until a response is received.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I fixed it by myself by changing

httpRequest.open('POST', path, true);

to

httpRequest.open('POST', path, false);

Now the async is set to false and the send methods waits until a response is received.

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