function hello() {
var arr = [];
$.get(url, function (data) {
var items = $(data).find("item");
$(items).each(function (idx, item) {
arr.push(item);
});
});
return arr; //undefined because nested loops are not finished processing.
}
How do I make sure that arr is populated before returning it?
asked Apr 2, 2014 at 7:39
Maximus S
11.2k20 gold badges82 silver badges165 bronze badges
1 Answer 1
There is no way to escape from asynchronous calls. You would need callbacks to get the result of the GET call.
function asynCall() {
var response;
// Ajax call will update response here later.
return response;
}
var responseFromFun = asyncCall(); // This will be undefined or null.
This is how your code works now. So response will always be undefined or null.
To get the response from Ajax calls pass a callback to the function when invoking it instead of assigning a response to it.
function asyncCall(callBack) {
var response;
$.get(...) {
response = someValueReturnedFromServer;
callBack(response);
}
// There wont be a return here
}
asyncCall(function(response){
// Do something with response now
});
The downside here is that if you are passing arr object (in your code) to some other function even that has to be changed to use callbacks !
answered Apr 2, 2014 at 7:51
GoodSp33d
6,3024 gold badges37 silver badges70 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Maximus S
Hey thank you. Until I ran into this problem, I guess I didn't actually understand how callbacks were constructed. Now I do! Just one more question to add. Why is it necessary to check if callback is a function like
typeof callback == 'function' as seen in some other posts related to callbacks?GoodSp33d
@MaximusS Its just to make sure that a function was indeed passed and not a number or anything. In above code
asyncCall("hello") is also valid but results in error when get call is completed as error handling is not done.lang-js