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
You can promisify ajax call by wrapping it in
Promise
. e.gAnd then you can consume data by using code below:
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
Don’t forget to add "async" in parent script