Day 52 of #100daysofjs

Introduction to Promises

Promises are a crucial concept in JavaScript that allow you to handle asynchronous operations in a more organized and manageable way. They were introduced as a native feature in ECMAScript 2015 (ES6) and have since become a fundamental part of JavaScript programming.

In JavaScript, asynchronous operations, such as fetching data from a server or reading a file, are typically executed using callbacks. While callbacks work, they can lead to what's known as "callback hell" - nested and tangled code that becomes difficult to read and maintain.

Promises were introduced to address this issue by providing a cleaner and more structured approach to handling asynchronous operations. A promise is an object that represents the eventual completion or failure of an asynchronous operation, and it provides a way to handle the result of that operation when it becomes available.

A promise has three states:

  1. Pending: The initial state. The promise is neither fulfilled nor rejected; it's still in progress.

  2. Fulfilled: The promise has been resolved successfully with a result.

  3. Rejected: The promise has encountered an error or failure.

The basic syntax to create a promise is as follows:

const promise = new Promise((resolve, reject) => {
  // Asynchronous operation or task
});

The promise constructor takes a callback function with two parameters: resolve and reject. Inside this function, you perform your asynchronous operation. If the operation is successful, you call the resolve function and pass the result. If an error occurs, you call the reject function and pass the error message or object.

Once a promise is created, you can attach callbacks to handle the resolved or rejected states using the then() and catch() methods:

promise.then((result) => {
  // Handle the fulfilled state (success)
}).catch((error) => {
  // Handle the rejected state (error)
});

The then() method is used to handle the fulfilled state, and it takes a callback function that receives the result of the successful operation. The catch() method is used to handle the rejected state, and it takes a callback function that receives the error object.

Promises can be chained together using multiple then() statements, allowing you to perform a sequence of asynchronous operations one after another. Each then() returns a new promise, which enables the chaining.

Promises offer a more structured and readable approach to handling asynchronous operations in JavaScript compared to traditional callback-based approaches. They have become a standard way to deal with asynchronous code and are widely used in modern JavaScript development.

Did you find this article valuable?

Support Arpan Mukherjee by becoming a sponsor. Any amount is appreciated!