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

194
Views
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 answers
Answer question

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 Report

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 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!