I want to turn an asynchronous function to the synchronous.
function fetch() { var result = 'snap!'; $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function messyCallback(data){ result = data; }); return result; } document.write(fetch()); The result always will be 'snap!', because $.getJSON run after fetch() is done.
My first idea was:
function fetch() { var result = 'snap!'; $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function messyCallback(data){ result = data; }); while (true) { if (result != 'snap!') return result; } } It doesn't work and also blow off the browser.
I read about generators and iterators in JS 1.7, but I have no idea how to apply it to my problem.
This question is not really about jQuery. Instead of $.getJSON could be any another asynchronous function.