DEV Community

Cover image for Asynchronous Code in JavaScript
Michael Liendo
Michael Liendo

Posted on

Asynchronous Code in JavaScript

Asynchronous Code

Laundry

When cleaning your home, it wouldn't be very time efficient to first put the clothes in the laundry and sit there and wait until the clothes are done before moving on to the dishes.

Ideally, you'd want to start some task, and while that task is running, start another task. That's what's known as working in an asynchronous (async) manner!

Just as it applies to the real world, async code also exists. As such, this section will specifically cover the following pieces of async code as they relate to JavaScript:

  1. Creating Callbacks Overview
  2. Creating Promises Overview
  3. Homework: Putting it all together

Creating Callbacks

covid dating

With some local businesses opening up, people are starting to spend time together at area restaurants.

Imagine you and a friend are outside of the United States and decide to go to a restaurant. The process is usually the same wherever you go: You both provide your orders to the waiter, the waiter goes off, while you two continue conversing. After a while your order comes back.

This is a callback in real life😲

Simply put, you asked for something (a meal) and when the food is done, you will be notified.

Here's a small code example of a callback
quarantine callback

In the above example, we first create a function that takes in as an argument, a function🤯. Remember that in JavaScript, functions can be passed around just like any other piece of data. Note that it's common to name this generic function callback.

This function, fetchQuarantineMood is in charge of generating a random mood, and then calling the passed in function (hence the name "callback") with that mood.

Now that we've seen an example of what a basic callback looks like, it's a good time to point out a common notion: When using a callback, the implementation details of the callback logic are not important. It's a black box.

The other part to consider, is that because this is asynchronous, any code we have after our call to fetchQuarantineMood will run. This notion of running our synchronous code first, then running our asynchronous code is known as the JavaScript event loop and is explained amazingly well in this YouTube video👇🏽

With a stronger understanding of callbacks, feel free to take a moment to review a more real world example below. I made sure to add comments to help understand what is happening, though you're encouraged to play around with the code as well.


Creating Promises

If the analogy for a callback is placing an order at a restaurant, the analogy for a promise is asking someone if they want to watch a movie.

async promise conversation with movie example

In the above situation, there're a few ways this could turn out:

Good: You can go to the movies🍿

Bad: You're going to Netflix and quarantine alone😩

And in the meantime...I don't know.

This maps directly to how JavaScript promises work. However, we don't say good, bad and I don't know.

Instead, we say resolved, rejected, and pending respectively.

Similar to before, let's take a look at what creating and using a basic promise looks like.

simple promise example

In the above example, fetchUser is a function and inside of its body, we return a new Promise. The Promise function expects a single function (a callback!) that gives us resolve and reject.

Now there's a lot of functions being thrown around here, but just note that resolve and reject are also functions. However, only one of them will be called based of off some condition--hence the if-statement.

Using a Promise

When calling a promise-based function, what is returned is an object whereby one of the properties we can use is then. This property is a function that when called, takes in two arguments: A function that will run if things go well (resolved), and another that will run with things do not (rejected).

🗒️ An important item to remember, especially when starting out, is that whatever value that we return from a promise, is wrapped in a promise. This allows us to chain promises together. You'll see an example of this in the example below.

Example: Promise Chaining and Error Handling

🚨Homework: Challenge Area🚨

In the above sandbox example, note that we are not checking for an error state. Let's fix that!

In the above sandbox:

  1. Create a function called createErrorMessage that will:
    • Take in as an argument, a "message".
    • Create an empty paragraph tag.
    • Return a paragraph tag that has its innerText set to the provided message.
  2. Change the addImageNodeToScreen function to be more generic so that it can accommodate adding any DOM node to the screen. Be sure to refactor areas where it's called.
  3. In the first .then of fetchUser, add a second argument.
    • This function will be called if there is an issue fetching data from the api.
    • This function should return an error message set to a string of your choosing, but beginning with "Error:" ie "Error: unable to fetch image"
  4. In the final .then of fetchUser, check if the given string startsWith Error:
    • If it does, call createErrorMessage with that string.
    • Else, call createImageNode as it currently is.
  5. Test out your solution by removing some characters from the randomuser.me/api string at the top of the file and then clicking the button.

You should see your error message!


As is JavaScript, there's much more that we could discuss when it comes to callbacks, promises, and asynchronous code in general.

However, I hope this serves as a practical guide to help you understand how to both use and create an async workflow!

Thanks for following along and I look forward to seeing your solutions, improvements, and thoughts in the comments!

🙏🏽 cover image and top image provided by icons 8

Top comments (0)