javascript - New to async programming. How do I get things to happen in proper sequence across different objects? -


i'm trying refactor program. had made work making ajax calls synchronous, i'd proper way. what's happening headline instantiated new headline headlines contains list of headlines. headlines.getrandom() selects random headline existing list, but, if list empty, makes ajax call fetch more headlines.

i can't quite wrap head around how make headline object constructor wait call complete without making 2 objects interdependent. stands, headline fails instantiated because it's trying instantiate object undefined since call hasn't completed.

i know callbacks, how can use callbacks cause 1 object wait on success of ajax call without getting lot of object incest?

headline = new headline(headlines.getrandom(true)); fillheadline(); 

here's code in context if you'd @ more of it. https://github.com/raddevon/onion-or-not/blob/true-ajax/js/js.js#l104

besides callbacks, mention. can use deferred objects , promises. example, jquery.deferred

there few advantages of using deferred/promises instead of callbacks:

  • promises can chained, possible wait several promises before doing something, e.g jquery.when() . callbacks bit more messy.
  • you can check state of promise, example display initial default value while waiting actual data.
  • it easier decouple producer , consumer of data. promises returned , passed along in procedural/sync style (as if actual data), helps in avoiding complicated chains of callbacks in execution path hard follow.

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -