Member-only story

JavaScript Promise: Know When To Use It and How It Works

Moon
Better Programming
Published in
6 min readFeb 15, 2021

--

Photo by Womanizer WOW Tech on Unsplash

Many developers who use JavaScript daily love to use the async/await syntax. It is not only easy to learn and use, but it can also make your code more readable and understandable. However, did you know that sometimes you need to use the Promise syntax rather than the async/await syntax?

In this article, I’ll explain how Promise works under the hood and when you should use it.

Prerequisite

You should already know the basic usage of Promise.

How Promise Works Behind the Scenes

Workflow of Promise
Workflow of Promise (by the author).

I think many of you already know what Promise’s stages are. Once you finish whatever you do inside a Promise constructor, it returns another Promise and waits for what you wrote in the constructor to be done. This will be fulfilled or rejected.

Let’s take a look at a simple example:

Can you guess the result?

It seems so obvious that 1 would be printed at first. Since setTimeout is an asynchronous function, you think, “It’ll be executed at some point later.” Then, you encounter Promise. “Hmm, a Promise is also an asynchronous thing, so I guess this would be executed after setTimeout because I met setTimeout first.”

So you’re pretty sure the answer is 1-2-3-4 or 1-3-2-4… which is wrong.

Many developers I’ve met have known that Promise is considered asynchronous, but they didn’t really know why it’s considered asynchronous.

I’ll put forth a few statements. See how many of them you feel are correct:

  • JavaScript is a single-threaded language. (O/X)
  • JavaScript has multiple task queues. (O/X)

--

--

Moon
Moon

Written by Moon

Frontend React w/ Typescript developer based in S.Korea. Interested in UX/Testing/FE. mgyang95@gmail.com

Responses (1)

Write a response