r/learnjavascript • u/PathOfTheProkopton • Nov 02 '18
Asynchronous JS
I have having trouble understanding asynchronous coding, specifically callbacks. I haven't tried to focus on promises or async/await because I want to get a handle on callbacks first.
I understand that asynchronous coding is like running one parts of code while you wait for some other code to finish its job, but why do callbacks work? What are they supposed to do, what do I write into my callback functions?
3
Upvotes
5
u/ucladurkel Nov 02 '18 edited Nov 02 '18
Think of it like going to a coffee shop. If a coffee shop were synchronous, the first person in line would order, the barista would make the drink, then call the person's name to give them their drink. Then, the next person in line can order. This is not efficient since everything is on hold until the previous step is complete.
Now, let's make it asynchronous. The first person in line, Alice, places her order, then steps aside. She has a "callback", which is to get her drink when her name is called. The barista can start up the espresso machine, then step away and take the next person's order. After some time, the barista has taken a few orders and started a few drinks, and then Alice's drink is ready. The barista calls her name, and Alice picks up her drink.
In pseudocode, this might look something like this:
Basically, synchronous code is when everything happens one thing after another. Asynchronous code allows you to start multiple tasks, and whenever they finish, the callback runs which contains whatever code you would have done after waiting synchronously.