Skip to content

Instantly share code, notes, and snippets.

@agirorn
Created November 18, 2016 10:44
Show Gist options
  • Save agirorn/dffdddd206c6cbfbc7138b5c40b7e959 to your computer and use it in GitHub Desktop.
Save agirorn/dffdddd206c6cbfbc7138b5c40b7e959 to your computer and use it in GitHub Desktop.
How do I return the response from an asynchronous call.....
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
callback(null, response); // Returning the response
}
});
}
var result
foo(function callback(data) {
result = data;
});
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`.
function foo() {
return new Promise(function(resolve) {
$.ajax({
url: '...',
success: function(response) {
resolve(response); // Returning the response
}
});
});
}
var result
foo().then(function(data) {
result = data;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment