Instead of writing helper methods, such as your fetch , that return a value, make them accept another function, the โreceiverโ, to pass their result:
function fetch(receiver) { $.getJSON("blah...", function(data) { receiver(data); }); }
Obviously, this is redundant, because exactly how getJSON already works, but in a more realistic example, the fetch function will process or filter the result one way or another before passing it.
Then instead of:
document.write(fetch());โ
You would do:
fetch(function(result) { document.write(result); });
Generators can be used to make asynchronous code much more linear in style. Every time you need some kind of asynchronous result, you have to run the function to start, and the generator will resume when the result is available. There will be some control code to ensure the operation of the generator. But this does not help much, because generators are not standard for browsers.
If you're interested, write a message about using generators to remove asynchronous code .
Daniel Earwicker
source share