skip to Main Content

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;
            }
      });
    }

2

Answers


  1. 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()
    
    Login or Signup to reply.
  2. 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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search