A Simple Beginner’s Guide to JavaScript Promises

Richard Oliver Bray
4 min readJan 6
Photo by Sai De Silva on Unsplash

Promises are a powerful tool in JavaScript but can take a while to understand and tend to confuse a lot of beginners. If you’re new to JavaScript, you might be wondering how to get started. That’s exactly what this article is for.

I’ll walk you through the basics of using promises in JavaScript and I’ll also cover how to handle errors that occur during the asynchronous operation, using the catch method.

TL:DR

If you prefer to learn via videos, you can get the gist of this article in a 1-minute TikTok video.

A simple explanation

Imagine a Promise in JavaScript is like a waiter in a cafe. Imagine you order a sandwich from the waiter, the waiter writes down your order and goes to the kitchen to prepare it.

While you’re waiting for your food you can continue to do other things, like chat with your friend or check your phone. You don’t have to sit around waiting for the sandwich to be ready.

Eventually, the waiter will return. If waiter brings the sandwich to your table then we say that the promise is resolved. At this point, you can either choose to eat the sandwich, or you can decide not to eat it. However, if something has gone wrong during the preparation of your food and the waiter has returned bringing bad news, we say that the promise is rejected.

This is a good analogy for how promises work in JavaScript.

A promise is an object that represents the eventual completion or failure of an asynchronous operation. Just like the waiter in the cafe, a promise represents something that will be done in the future, but you don’t have to wait around for it to happen.

Writing a Promise

Writing a Promise in JavaScript is fairly simple. You use the Promise constructor like so:

const myPromise = new Promise((resolve, reject) => {
// asynchronous code goes here
});

// OR

function executor(resolve, reject) {
// asynchronous code goes here
}
const myPromise = new Promise(executor);

The Promise constructor takes a function called the "executor" as an argument. This is responsible for performing the asynchronous operation…

Richard Oliver Bray

Co-founder of orva.studio. Building digital products and teaching others to do the same. Saved by grace.