JavaScript - Promises in JavaScript

A Promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation. It is used to handle tasks that take time to complete, such as fetching data from a server, reading files, or waiting for a timer. Promises help manage asynchronous code more effectively than traditional callback functions and make the code easier to read and maintain.

A Promise has three possible states:

  1. Pending – The initial state. The operation has not completed yet.

  2. Fulfilled – The operation completed successfully and returned a result.

  3. Rejected – The operation failed and returned an error.

A Promise is created using the Promise constructor, which takes a function as an argument. This function receives two parameters: resolve and reject.

Example:

let myPromise = new Promise(function(resolve, reject) {
    let success = true;

    if (success) {
        resolve("Operation completed successfully");
    } else {
        reject("Operation failed");
    }
});

To handle the result of a Promise, the .then() and .catch() methods are used.

  • .then() is executed when the Promise is fulfilled.

  • .catch() is executed when the Promise is rejected.

Example:

myPromise
.then(function(result) {
    console.log(result);
})
.catch(function(error) {
    console.log(error);
});

Promises can also be chained, allowing multiple asynchronous operations to run in sequence.

Example:

let promise = new Promise(function(resolve) {
    resolve(10);
});

promise
.then(function(num) {
    return num * 2;
})
.then(function(num) {
    console.log(num); 
});

In modern JavaScript, Promises are widely used with APIs such as fetch() to handle asynchronous tasks more efficiently. They also form the foundation for the async and await syntax, which further simplifies asynchronous programming.