Understanding Promises and Async/Await in JavaScript

JavaScript ~ 8 minutes

# Welcome to Async JavaScript

Hello and welcome! In this tutorial, we will learn about Promises and async/await in JavaScript. These ideas help us handle work that takes time, like loading data from a server or reading a file.

Imagine you order food at a restaurant. You do not stand in the kitchen and wait. You sit down, and the waiter brings the food when it is ready. JavaScript works in a similar way. It starts a slow job, then continues with other work, and comes back when the job is done. We call this asynchronous code.

Do not worry if this idea is new. We will use easy examples.

What you will learn

  • Why we need asynchronous code
  • What a Promise is and how it works
  • How to use then and catch
  • How to write cleaner code with async and await

You should know basic JavaScript, such as variables and functions. We will run our code with Node.js. Let us check that it is ready.

Check Node.js version
Code Copied to Clipboard

# A first look at waiting

If you see a version number of 18 or higher, you are ready. Newer Node.js versions also include the fetch function, which we will use later. If your version is older, please update it from the official Node.js site.

Now, please create a file called async-demo.js. We will write all our examples there.

Let us begin with the simplest way to see waiting in action. The function setTimeout runs a piece of code after some time. We give it a function and a number of milliseconds. Watch the order of the messages carefully. This will show you how JavaScript does not stop and wait. It moves on to the next line, and returns to the slow job later.

Please type the code below.

Waiting with setTimeout
Code Copied to Clipboard

# Run and observe

Let us run the file now. Please look at the order of the output. You may expect the messages in the order 1, 2, 3. But that is not what happens.

You will first see message 1, and then message 3. After two seconds, message 2 appears. This is because setTimeout does not block the program. JavaScript puts the timer aside and continues with the next line. When the time is up, it runs the waiting code.

This behavior is very helpful. On a website, it means the page does not freeze while data is loading. But it also creates a new problem. How do we write code that must run after a slow job is done? In the past, people used callbacks inside callbacks, and the code became hard to read. Promises were made to fix this.

Run the demo
Code Copied to Clipboard

# What is a Promise?

A Promise is an object that stands for a value that you will get in the future. It is just like a promise from a friend. At first, you do not have the result. Later, the promise is either kept or broken.

A Promise has three states.

The three Promise states

  • Pending: the work is still going on
  • Fulfilled: the work finished well, and we have a value
  • Rejected: the work failed, and we have an error

We create a Promise with new Promise(). It takes a function with two helpers: resolve and reject. We call resolve when the job succeeds. We call reject when it fails.

To use the result, we chain .then() for success and .catch() for errors. Let us write a small function that waits and then gives back a message.

Create and use a Promise
Code Copied to Clipboard

Why chaining is useful

Each .then() returns a new Promise. This means you can join many steps one after another. The result of one step goes into the next step. This is called chaining.

And there is one more good thing. A single .catch() at the end can catch errors from any step above it. So you do not need to check for errors again and again.

There is also .finally(). It runs at the end, whether the work succeeded or failed. It is perfect for cleaning up, like hiding a loading spinner. You can read more in the MDN guide on using Promises.

# Meet async and await

Promises are good, but long chains of .then() can still look messy. So JavaScript gave us a nicer way: async and await. They do not replace Promises. They are just a cleaner way to use them.

Here are the two rules. First, put the word async before a function. This makes the function always return a Promise. Second, inside an async function, you can put await before any Promise. The function then pauses at that line until the Promise is done. Then it gives you the final value directly.

The code now looks like normal, top to bottom code. It is much easier to read.

Remember these rules

  • async goes before the function
  • await can be used only inside an async function
  • await waits for a Promise and gives its value
  • The rest of the program does not freeze while waiting

Let us rewrite our earlier example with these new keywords.

Using async and await
Code Copied to Clipboard

# Handling errors with try and catch

What if something goes wrong? With async and await, we handle errors in the same way as in normal code. We use try and catch.

We put the risky code inside the try block. If any awaited Promise is rejected, JavaScript jumps right to the catch block. There, we can show a friendly message to the user.

This is very important when we talk to a server. The network can fail, the server can be down, or the data can be wrong. A good program is ready for these problems.

Now, let us do something real. We will fetch data from a free test website. The fetch function returns a Promise. We await it to get the response. Then we await response.json() to read the data. The address we use is a free service for practice, so it is safe to try.

Fetch data safely
Code Copied to Clipboard

# Run the fetch example

Please add this code to a new file named fetch-demo.js, and save it. Now, let us run it with Node.js. You need an internet connection for this step.

If everything is fine, you will see the title of a sample blog post printed in your terminal. It happens after a short moment, because the data comes from a server far away.

If you see the message Something failed, please do not worry. Your internet may be off, or the proxy may block the request. That is actually good news, because it shows that our try and catch code works as planned. Check your connection and try again. Notice how short and clear the code is. This is why most developers love async and await.

Run the fetch example
Code Copied to Clipboard

# Running tasks together

Sometimes we have many slow jobs that do not depend on each other. If we await them one by one, the total time becomes long. A better way is to start them all together and wait for all of them at the same time. For this, we use Promise.all().

It takes a list of Promises. It gives back one Promise that is fulfilled when all of them are done. The result is a list of values in the same order. If even one Promise fails, the whole thing fails.

When to use Promise.all

  • When the jobs do not depend on each other
  • When you want a faster total time
  • When you need all results before you continue

Look at the small example below. Both waits run at the same time, so the total time is about one second, not two.

Promise.all in action
Code Copied to Clipboard
Mistakes to avoid

Please read these points with care. They are the most common problems with async code.

First, do not forget the await keyword. If you forget it, you get a pending Promise instead of the real value. Then you may see Promise { <pending> } in your output, and wonder why.

Second, do not use await inside a normal function. It only works inside a function marked with async. Otherwise, JavaScript shows a syntax error.

Third, always handle errors. A rejected Promise that nobody catches can crash your program, or it can fail silently.

Quick checklist

  • Did you write async before your function?
  • Did you put await before each Promise?
  • Is your risky code inside try and catch?
  • Can independent jobs run together with Promise.all?

With these habits, your async code will be clean and safe.

# Summary and next steps

Great job! You have reached the end of this tutorial. Let us remember what we learned.

Asynchronous code lets JavaScript keep working while it waits for slow jobs. A Promise stands for a future value, and it can be pending, fulfilled or rejected. We can use .then() and .catch() to handle the result. The async and await keywords make this code look simple and clean. We use try and catch to handle errors, and Promise.all to run jobs together.

What to do next

  • Fetch data from a real API and show it on a web page
  • Learn about Promise.allSettled and Promise.race
  • Study the event loop to see how JavaScript manages waiting
  • Read the MDN guide on async functions

Async code feels hard at first, and that is normal. Keep trying small examples, and it will become natural. You are doing very well!