Sign up ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I was wondering why functions that parses JSON files always use callback functions instead of just returning loaded response text? An example here and here. If it is possible, how would I return this value instead of callback'ing it?

share|improve this question

closed as off-topic by Tim Holt, Jari Komppa, Noctrine Apr 20 '14 at 15:00

  • This question does not appear to be about game development within the scope defined in the help center.
If this question can be reworded to fit the rules in the help center, please edit the question.

    
This question doesn't really have anything to do with game development specifically, it's a better fit for Stack Overflow. – Cupcake Apr 20 '14 at 8:33

1 Answer 1

up vote 1 down vote accepted

The functions use AJAX in the form of the XMLHttpRequest object (or "XHR" for short). Thus, by definition, they're asynchronous.

Because JavaScript runs in a single UI thread in modern browsers, making such a network call synchronously would lock the browser UI while it waits for the file request to complete, making it unresponsive and causing an extremely undesirable user experience. Thus the asynchronicity.

Because the functions are asynchronous, you must have a callback function to handle the asynchronous response when it completes. You could immediately return a value from an asynchronous function, but that value could never be the result of the file request, since that would basically make the function synchronous again.

share|improve this answer
    
Thanks for your explanation. I guess I'll have to get used to JavaScript's asynchronous character. – Winged Apr 20 '14 at 9:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.