Posts

Showing posts with the label ajax

How do I return the response from an asynchronous call?

Image
How do I return the response from an asynchronous call? I have a function foo which makes an Ajax request. How can I return the response from foo ? foo foo I tried returning the value from the success callback as well as assigning the response to a local variable inside the function and returning that one, but none of those ways actually return the response. success function foo() { var result; $.ajax({ url: '...', success: function(response) { result = response; // return response; // <- I tried that one as well } }); return result; } var result = foo(); // It always ends up being `undefined`. @MaximShoustin I've added a JavaScript only answer (no jQuery) but like Felix said - "How do I return the response from an AJAX call" is really a nice way to say "How does concurrency work in JavaScript". Not to mention Angular's $http is very similar to jQuery...