r/learnjavascript • • 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

3 comments sorted by

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:

//synchronous
function makeDrinkSynchronously() {
     create new drink
     start machine
     wait for drink to finish
     return drink
}
for customer in line {
    customer.placeOrder()
    drink = barista.makeDrink() //this takes 3 minutes to finish
    customer.takeDrink(drink)
}

//asynchronous
function makeDrinkAsynchronously(callback) {
    create new drink
    start machine
    whenever the machine finishes { //don't wait for this to happen
          callback(drink)
    }
}
for customer in line {
    customer.placeOrder()
    barista.makeDrink(customer.takeDrink)
}

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.

2

u/everek123 Nov 02 '18

Callback functions are basically functions that fire when the main function finished running. Since in async code you sometimes have to wait for the result of one function to run another you often have a function that runs when the first process finishes- those are callback functions. I personally do not recommend using callbacks because they lead to 'callback hell'

1

u/HealyUnit helpful Nov 02 '18

Firstly, /u/ucladurkel provides an excellent description that's all the better because I'm sitting in a coffee shop right now. So, just read theirs if you don't wanna bother with mine.

The Internet/Asynchronicity

Before I answer your question, let's talk about the internet itself. The internet, besides containing pictures of cats, is basically a series of requests and responses. So if I go to someSite.com/catPics/Fluffy.jpg, I'm not opening a file on their computer, in a folder called catPics, named Fluffy.jpg. Instead, I'm sending a request to someSite, particularly to the route /catPics/Fluffy.jpg, and expecting the site to respond a certain way. That could be a picture, it could be the metadata for the picture, or it could be something else entirely. For example, I might respond by saying "Fluffy is a 2-year old scotttish fold". That's all the internet is: I send you a request, and you know how to respond to it some way.

This is part of a bigger concept called 'asynchronous programming'. As a comparison, Synchronous programming can be thought of like a recipe:

Cookie Recipe:
1. Get bowl
2. Add ingredients
3. Bake

In other words, you can't add ingredients until you get a bowl, and you can't bake until you add ingredients. These operations are synchronous, happening in a set order, and one does not happen until the previous one completes.

Asynchronous code, on the other hand, says "go do this thing, and lemme know when you get back. In the meantime, I'll do something else":

Cookie Recipe:
1. Get bowl
 - Meanwhile, have friend mix fruit punch. When done, put in jug.
2. Add ingredients
3. Bake

Your friend mixing the fruit punch is not dependent on getting the bowl, and adding ingredients is not depending on the fruit punch being mixed. It's asynchronous with regards to the rest of the recipe.

Where/When

There are generally two things that would require asynchronous stuff. The first is what I've mentioned before: making a request to a remote resource. In this case , your response time is going to depend on factors like network latency (lag), the particular nature of your request, the software running on both computers, etc., and you need to respond whenever that gets back.

The second is user actions. If I have a particular function that happens when the user clicks a button, that action is necessarily asynchronous, as I again don't know when exactly the user will click the button. So I might some code that says "whenever user clicks button, do the thing".

Callbacks

Now, here's the issue. Because of this asynchronous request/response format, you don't know when I'll get around to answering (or in the case of the button click, clicking the button). I might answer in 10 ms, or I might take 10 years. Worse yet, I might have a function that expects a response after 10 ms, and gets that response at 10.1 ms instead. Either way, if I don't have a function that's called whenever the response gets back - we've named this a "callback" - I'd 'miss' that response.

And that's basically all a callback is. For any piece of code for which you don't know when it's gonna run/finish running, you can use a callback to be 'called' whenever that function gets 'back' from what it's doing.

Enough talking. Let's look at an example, from jQuery's $.get() function:

$.get('https://jsonplaceholder.typicode.com/posts',function iGotBack(response){
    console.log(response);
})

The iGotBack() function is our callback. Callbacks are usually given as the last argument in an asynchronous function, and usually contain as their own arguments at least response parameter (and often status or errors, if applicable).

Here's a jsfiddle example where I've put the request inside its own function, and you can see how long it takes each time: https://jsfiddle.net/qsbL8x65/. Take particular note that each time you run it, it takes a different amount of time.