Callbacks & Promises

Async

There are some functions in JavaScript that take a decent amount of time to complete. This is due to the fact that JavaScript is the language of the web and thus some operations such as fetching data from a server might take some time to complete.

These functions are called asynchronous functions, that is functions that happen in the background while the rest of the code executes. Likely JavaScript includes support for those functions.

Learning Objectives

  • Synchronous VS Asynchronous in javaScript.
  • How to handle asynchronous code in javascript.
  • How JavaScript queues asynchronous events.
  • What a callback function is?
  • What a promise is?
  • Callbacks VS Promises.
    • What is callback hell.
    • When promises are better than callbacks.
  • What the .then() function does?

Introduction to Callbacks

Until recently the asynchronous functions were handled with callbacks. In certain circumstances callbacks are still used quite a lot. But what is a callback?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. MDN

So, basically callbacks are functions that get passed into other functions. Let’s see an example.

myElement.addEventListener("click", function(){
  // do something here!
})

In this example, the function addEventListener() takes a callback (the "do something here" function) and then calls it when myElement gets clicked.

This pattern is something that you should be familiar with in JavaScript code. Although we can use the example above in several situations there are other situations where using callbacks can be tricky. For example if we have to chain several callback functions together in a specific order.

Therefore in the rest of this topic we will see patterns and functions that will help you to get out of this Callback hell. So skim through this article before moving on. If you prefer a video instead take a look at this.

Introduction to Promises

Although there are multiple ways that we can handle asynchronous code in JavaScript, Promises is the most common used when using other libraries or frameworks. It is very useful to know what they are and how we can use them.

Basically a promise is an object that might produce a value at some point in the future.

Let’s see an example. We have a function called fetchData() that fetched data from a server. This function returns these data as an object that we can use in our code.

const fetchData = function() {
  // fetch data from an API
  // clean it up a bit and return it as an object:
  return data
}

The problem here is that the function fetchData() takes some time to fetch the data. Thus, if we don’t tell that to our code it will assume that everything happens instantly.

So if we try to do the following:

const myData = fetchData()
const someData = myData['do something here']

We will have problems. When we try to extract someData out of the returned data, the function fetchData() will most likely still be fetching. Therefore the myData will not be the expected data, but instead it will be undefined.

So we need somehow to tell our code to wait until the data is done fetching in order to continue. Promises solve these kind of problems. Basically promises allow us to do the following thing:

const myData = fetchData() // if this is refactored to return a Promise...

myData.then(function(data){ // the .then() tells it to wait until the promise is resolved
  const someData = myData['do something here'] // and THEN run the function inside
})

Promises are also used in many other cases beyond fetching data. Thus it is really useful to learn now those things.

Study

  1. A good starting place is this article. It’s a short article and to the point.

  2. Watch the next video. The other videos in the series aren’t needed at this point, but feel free to watch them if you want to. The video also mentions the ES5/ES6 issue, don’t worry about that either. All major browsers support Promises and we will teach you how to support older browsers in a later lesson.

  1. Watch the next video to understand how asynchronous code works in JavaScript.

  1. Read Chapter 2: Callbacks and Chapter 3: Promises from You Don't Know JS. In Chapter 2, the author explains the problems with callbacks and why callback hell will be your worst enemy. In Chapter 3, you go deep into the how and why of promises. This chapter is not the easiest read, but you’ll be a promise professional if you take the time to properly digest it. It’s worth the effort.

Additional Resources

In this section you can find a lot of helpful links to other content. This is a supplemental material for you if you want to dive deeper into some concepts.

  1. Another useful article about Callback functions in JavaScript is this.

  2. The MDN Documentation for Promises. It might not be the best resource for learning all about them, but once you’ve read a more friendly article or tutorial, this will probably be the place you return to for a refresher.

  3. If you need more repetition to promises this video and this one too are both really nice introductions.

  4. Another good introduction is this tutorial.

Leave a Reply