Skip to content

Instantly share code, notes, and snippets.

@robwilson1
Last active August 21, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robwilson1/aa9b66f0f4c3105f957dcac3b25523fc to your computer and use it in GitHub Desktop.
Save robwilson1/aa9b66f0f4c3105f957dcac3b25523fc to your computer and use it in GitHub Desktop.
Async

Async and callbacks

When dealing with code, you often come across something about asyncronous and syncronous streams.

Imagine you go to McDonals and you order a Big Mac, in a syncronous world, no one else can place an order until your Big Mac has been cooked, bagged up and delivered to you. In an async world, when you order the Big Mac, the order is sent to some other people who cook it and bag it, whilst the guy who took your order can continue to serve other customers.

When dealing with JavaScript we often need to do things in order, to make it predictable and bug free. We also need to wait for something to happen before proceeding.

Callback functions

What we need to do is tell our code to execute some function once the data is avaliable. We essentially say, 'Hey once a second elapses, can you call me to give me the number? This is why we call this method of async code a callback function.

Let's take a look:

   var printNum = function() {
       setTimeout(function() {
           console.log(100)
       }, 1000)
   }
 
   printNum()
}

In this snippet, we call printNum, this then calls an inbuild JavaScript function called setTimeout. This takes two parameters, the first is the callback function, the second is the time in milliseconds to wait. Note the time is minimum time, it might take longer!

This is possible thanks to the fact that in javascript, functions themselves can be passed around as paramaters! Just like numbers or strings. This makes JavaScript very powerful indeed So in this example, after one second, setTimeout itself calls the function we defined in-line. We can also call an external function like so:

    var callbackFunc = function() {
        console.log('Called');
    }
    var printThing = function() {
        setTimeout(callbackFunc, 1000);
    }
  
    printThing();

Notice that when calling an external function here I cannot pass an argument with setTimout. If I wanted to however, I could do something like this:

    var callbackFunc = function(num) {
        console.log(num);
    }
    var printThing = function() {
        setTimeout(function() {
            callbackFunc(100)
        }, 1000);
    }
  
    printThing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment