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

198
Visualizações
How to wait for AJAX success handler to finish executing?

I am returning an object within my AJAX success handler, which I need before my code executes any further. However, when using AJAX, it does not wait for the success block to finish executing, and hence printing the value as of myLayer variable as undefined as the console.log(mylayer) line gets executed before a value is returned by the success handler. How can I wait for the success handler to return the userLayer object so that the myLayer value is not undefined?

P.S. no need to worry about how the datatype and definition of myLayer and userLayer variables, as they are correct in my code and are taken care of. Didn't include it here so as to keep the question simple and to the point. I've been stuck on this problem for really long. Any help will be deeply appreciated :)

Calling the AJAX function

myLayer = this.addUserLayerTreemail(userLayer);
          
// This always prints "undefined" as it gets executed before the AJAX
// success handler returns the value
console.log(myLayer)

Defining the AJAX function

addUserLayerTreemail(userLayer) {
 
  let configData = {"searchText": "search", "searchType" : "treemail"};

  $.ajax({
    url: "../apis/mySearch",
    method: 'GET',
    dataType: 'json',
    data : configData,
    success: response => {

      userLayer.query().where(response).run((data) => {
          userLayer.add(data);
      });

       // I need this object to be stored in the myLayer variable (when calling the 
      // function above) after the success handler of AJAX function is executed. 
     // Currently, it only returns this variable after console.log(myLayer) above 
    // which yields in the myLayer variable to print "undefined".
       console.log(userLayer);
       return userLayer;
            }
      });
    }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can get get async code look like sync code by using "async" and "await". Use keyword "await" at when you need returned value of async function.

If function uses "await" it must have "async" keyword before function definition

async addUserLayerTreemail(userLayer) {

    let configData = {"searchText": "search", "searchType" : "treemail"};

    var response = await $.ajax({
        url: "../apis/mySearch",
        method: 'GET',
        dataType: 'json',
        data : configData,
    });
      
      
    userLayer.query().where(response).run((data) => {
        userLayer.add(data);
    });

    console.log(userLayer);
    return userLayer;
}

Don't forget to add "async" in parent script

async function main(userLayer){
    myLayer = await this.addUserLayerTreemail(userLayer);
          
    console.log(myLayer)
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can promisify ajax call by wrapping it in Promise. e.g

  async function addUserLayerTreemail(userLayer) {
  let configData = { searchText: "search", searchType: "treemail" };

  return new Promise((resolve, reject) => {
    $.ajax({
      url: "../apis/mySearch",
      method: "GET",
      dataType: "json",
      data: configData,
      success: (response) => {
        userLayer
          .query()
          .where(response)
          .run((data) => {
            userLayer.add(data);
          });
        resolve(userLayer);
      },
      error: (error) => {
        reject(error);
      },
    });
  });
}

And then you can consume data by using code below:

async function print() {
  try {
    myLayer = await this.addUserLayerTreemail(userLayer);
    console.log(myLayer)
  } catch (error) {
    console.log(error)
  }
}

print()
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