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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.