Created
November 18, 2016 10:44
-
-
Save agirorn/dffdddd206c6cbfbc7138b5c40b7e959 to your computer and use it in GitHub Desktop.
How do I return the response from an asynchronous call.....
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function foo(callback) { | |
$.ajax({ | |
url: '...', | |
success: function(response) { | |
callback(null, response); // Returning the response | |
} | |
}); | |
} | |
var result | |
foo(function callback(data) { | |
result = data; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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