Asynchronous: Callbacks

JavaScript is synchronous by default and is single threaded. This means that code cannot create new threads and run in parallel.

Lines of code are executed in series, one after another, for example:

const a = 1
const b = 2
const c = a * b
console.log(c)
doSomething()

JavaScript was born inside the browser, its main job, in the beginning, was to respond to user actions, like mouse clicks.

We needed a way to say “do this when the user clicks that button”.

The browser implemented a way to do it by providing a set of APIs.

We’re not going into the DOM and event handlers in this masterclass, because that’s a big topic on its own, that’s not pure “JavaScript”. But I need to introduce them briefly to explain asynchronous coding.

In this example we have document.querySelector() which lets us select the item with the id attribute set to button. Then we call addEventListener() to attach an event handler to the click event:

document.querySelector('#button').addEventListener('click', () => {
  //this function is executed when the mouse is clicked
})

The second argument to addEventListener is this arrow function:

() => {
  //this function is executed when the mouse is clicked
}

We call this a callback function.

It is only executed when the browser decides it should run, which in this case is when the user clicks the button.

So the browser provides us a way to defer the execution of the function in the future.

And in the meantime it will keep executing other lines of JavaScript in our program, without stopping to wait when the user will click the button.

Lessons in this unit:

0: Introduction
1: ▶︎ Callbacks
2: Timers
3: Promises
4: Async functions
5: Chaining promises
6: Orchestrating promises