Skip to content
promise in js

Promise in JavaScript

In this post, I’ll thoroughly explain the concept of Promise in JavaScript. We’ll cover the coding part later, but now let’s focus on where, what, and why behind the Promise.

Asynchronous programming

What does Asynchronous mean?

The simple definition of asynchronous means not at the same time, that’s the opposite of synchronous. Don’t worry, it’s simpler than it sounds. For example, in most programming languages, we have a print statement, and in JavaScript, we have console.log().

// Synchronous Code

// Output

The above code is synchronous, i.e. it executes one job/line after another and so on. But, there are some tasks that can take variable time, such as performing a complex calculation, uploading a file, or downloading data from the server. These tasks don’t fit well in between the synchronous tasks.

For example, in the code below, we are trying to get a name from the server and display it immediately. Printing/displaying the name is a synchronous task i.e. it happens immediately but to get the data from the server it can take some time and the correct way to handle this situation is to wait for the data to arrive and then print it out.

// Synchronous execution
const name = getNameFromServer();
console.log(name); // Undefined

// Asynchronous execution
const name = getNameFromServer();
// wait for server response
console.log(name); // John Doe

Just wait for async tasks to finish?

Okay, this sounds fair, why can’t we wait for all asynchronous tasks to finish and then execute the rest of the synchronous code?. Let’s see what happens when we visit a website, and how all the resources load in the background.

// Resources loading for a website
// Now the site is ready

Suppose the buttons are loaded instantly and then the time taken to load the video or image might take a while until then the user is shown a blank page and in the worst case, some resources might fail to load. This inconsistency in time should be handled carefully, or else everything will result in a huge mess.

Handling asynchronous tasks

We must wait for the asynchronous task to complete but meanwhile continue other possible synchronous tasks. One of the real-world examples is when we see a loader that our search results are loading or the form is being submitted.

The real problem

We can wait for an asynchronous task to finish, but we might want to do something else after the asynchronous task is finished or at least know when an asynchronous task has been completed. Suppose, I want to update the username on a web page and once I receive a confirmation from the backend server, only then I can let the user know that the change has been made successfully.

The concept of promise

Let’s start with a simple story. I promise you that I’ll give you candy 🍬. Now, there are three possibilities,

  1. I give you the candy and keep my promise
  2. I fail to give the candy and break my promise
  3. I am in the process of going to the shop to get you candy.

Similarly, a promise can exist in three states

  • Fulfilled (successful)
  • Rejected (failed)
  • Pending (processing)

Real-world promise usage

Websites or technically any software and all the data we see comes from servers/computers across the world and due to network latency/delay, some operations happen asynchronously. The time needed for a client(browser) to request data from the server and the server to search the database to send a response back to the browser is what causes a small delay. (Network speed also affects this). In situations like these, the JavaScript on the frontend/backend can use promises to handle all the asynchronous operations and provide a great user experience by letting the user know the status of the task happening in the background.

JavaScript and Promises

JavaScript takes full advantage of the promise concept by providing separate methods/functions for both fulfilled and rejected cases. This way we can program what to do next if a promise is successful or show an error message on rejection. And the concept/applications of promises doesn’t stop here, modern browser APIs like fetch also use promises to facilitate asynchronous tasks.

Modern web development revolves around the concept of async because thinking and programming in async is the main pillar to abstract all the work happening in the background and make sure operations are performed in the desired order. I hope through this article you are able to understand how a promise works. Where do you think you can integrate promises in your next project?