How to assign the return value of a function containing a getJSON() request to a variable?
I have actually been trying to figure this out for three days and it's driving me bonkers.
I believe the answer lies in deferred objects or promises or something of that nature, but I've tried to implement several of these solutions (from several examples) and got various errors.
This is what I want to achieve:
- function fn1() {
- $.getJSON("/path", function(results){
- return results.a_key; // this is a string
- });
- }
- my_var= fn1(); // i want this to equal the return value of fn1()
- alert(my_var); // this is alerting undefined instead of the value returned from fn1().
I know it's bad form, but a specific code example that achieves the desired results would be appreciated as I can't currently make sense of the theoretical solutions ie wait until the getJSON() is finished and
then do something.