I am trying to wrap my head around the nature of asynchronous code. What I understand so far is that you have callback functions instead of returning values, so everything that would have been done with the return value goes to the callback function.
But what if the state is changed, when the return value would affect the whole program.
Take for example the Quote Machine Challenge. I get the JSON from the Quotes API and in the callback function I put the code that changes the html to show the newly retrieved quote.
But I want to be able to send the quote text also to the twitter-button listener.
So usually in synchronous code I’d have a global variable which would be updated by a getQuote() function and given as a parameter to the listener of the post to twitter function.
In asynchronous I see two possibilities:
- Define a global variable and change its value in the callback function.
This appears, uhm, clumsy to me. If I need to change the code I have to take at minimum 2 places into account instead of one. And due to the nature of asynchronousity, I will never know whether the variable is already at the new value or not.
- Nest all follow up code within the callback. In the case of the Quote Machine this would mean I have the event listeners within the getJSON callback. Which would mean I would have the event listener for the new quote button within the callback of getJSON, while calling getJSON itselfto get the next quote and so forth. While this is absolutely doable it seems wrong to me, nesting deeper and deeper. The contexts will have to remain in memory I think and I’d use more and more memory without need,it seems.
While this might not be a problem in the Quote Machine, I do not want to take up a bad coding style.
So to make the long story short, is there another way? Do I miss something?