Skip to content
Promise 101 - JavaScript

Promise in JavaScript : 101

In JavaScript, a promise is an object that returns a value in the future. First, I would like to highlight that promises make asynchronous programming possible. In this post, we’ll learn how to get started with promises in JavaScript.

What is a promise in programming ?

It’s the same as in the real world, maybe better 😏. Say, I promise you I will give you an ice cream, the moment I say this you know I promised something but at this moment my promise’s state will be pending until I either give you or break my promise. It can be successful or fail in the future.

TLDR; I’ve written an almost no-code explanation post on the concept of promises and async programming, Promise in JavaScript.

Promise in JavaScript

A promise in JS is basically an object and can exist in three states,

  1. Pending (processsing) ⏳
  2. Fulfilled (successful) ✅
  3. Rejected (failed) ❌

Where do we use promises and why?

It is essential to understand why we are using promises in the first place. There are many operations on the frontend or anywhere which might happen asynchronously i.e they might take some time to complete. Ex: downloading an image or uploading a file. In such cases we need to wait for the task to complete but, still allow users to perform other operations and inform that this task is in process.

Show me the code

Alright! let’s start our consoles 🚀 here’s the basic Syntax

const promise = new Promise(function (resolve, reject) {
  // carry out async task here
  // Right now the state is pending 🟡
  // it might take some time

  // if sucess call resolve with result
  resolve("Success 🟢");
  // if fail call reject with result/error message
  reject("Fail 🔴 ");
});

promise.then((result) => console.log(result));

Explanation

First, we’ve defined a promise. For every promise we can pass two functions as parameters resolve and reject, the first one is called when the promise is successful and the other when it fails. These are also known as callback functions because they are called at a later point of time when the async code in the promise has finished executing.

In the end, we can see a line with promise.then(), this means that it is executed when the promise is settled. Initially, the promise is in a pending state, and later the promise is settled when it either resolves/rejects.

A simple example

You can try running the below code in the browser console.

const promise = new Promise(function (resolve, reject) {
  // carry out async task here
  console.log("Beep boop bop!");
  const result = true;
  // it might take some time
  if (result) {
    resolve("Yes! we did it 😀");
  } else {
    reject("Nope something went wrong 😐");
  }
});

promise.then((result) => console.log(result));

Beep boop beep!

// if result true
Yes! we did it 😀

// if result false
Nope something went wrong 😐

then, catch and finally

then

The .then() is used to execute the callback methods, all promises are thenable in nature. In the first argument, a callback function is called when the promise is fulfilled and the second when the promise is rejected, both of them are optional parameters. We can also chain the promises using .then() i.e first we execute on .then and then the next and so on. Chaining is particularly useful when we need to perform multiple asynchronous tasks one after another.

promise.then(onFulfillment, onRejected);

catch

The catch() method, as usual, is used for error handling. In simple words, we use the catch method to catch the rejected promise.

promise.catch((errorMessage) => console.log(errorMessage));

finally

The finally() method is like the regular finally we use, as the name suggests this is used to execute the code after a promise is settled i.e either fulfilled or rejected. I’ve used it several times to hide the loader after an async task is finished.

promise.finally(() => stopLoader());

Conclusion

So, that’s all folks 🙌, we’ve covered the basics now open the console and see how the promise works. Promises are everywhere, the fetch method that the browser provides for API requests is an abstraction of promises.
What are your thoughts?

Tags: