DEV Community

Deepak jha
Deepak jha

Posted on

Javascript: Promises

JavaScript Promises are a language feature that makes it easier to handle asynchronous code in JavaScript. Asynchronous code is code that doesn’t execute linearly but runs in the background while another code continues to execute. This is often necessary when dealing with things like network requests or user input, which can take an unpredictable amount of time to complete.

One way to handle asynchronous code in JavaScript is to use callbacks. A callback is a function that is passed as an argument to another function and is executed after the first function completes. While callbacks can be effective, they can also lead to what is known as “callback hell,” where the code becomes deeply nested and difficult to read and maintain.

This is where Promises come in. A Promise is an object that represents the eventual completion or failure of an asynchronous operation. Promises provide a cleaner, more readable way to handle asynchronous code by allowing you to chain together multiple async operations, rather than nest them.

To create a Promise, you use the Promise constructor, which takes a function as an argument. The function is called the "executor function," and it has two arguments: resolve and reject. The resolve the function is called when the async operation completes successfully, and the reject function is called when it fails.

Here’s an example of a Promise that simulates an async operation that takes two seconds to complete:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('The async operation is completed');
  }, 5000);
});
Enter fullscreen mode Exit fullscreen mode

To use the Promise, you call its then method, which takes two arguments: a callback for when the Promise resolves, and a callback for when it rejects. Here's an example of how you might use the then method:

myPromise.then(
  result => console.log(result), // this callback function is called when the Promise resolves
  error => console.log(error) // this callback function is called when the Promise rejects
);
Enter fullscreen mode Exit fullscreen mode

Promises also have a catch method, which is a shorthand for calling then with a second argument that handles any errors that might occur. Here's an example of how you might use the catch method:

myPromise.then(result => console.log(result)).catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

One of the key benefits of Promises is that they can be chained together. This allows you to create a series of async operations that execute one after the other, rather than nesting them. Here’s an example of chaining Promises:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('The async operation has completed');
  }, 3000);
});

myPromise
  .then(result => {
    console.log(result);
    return 'This is the next async operation';
  })
  .then(result => console.log(result))
  .catch(error => console.log(error));
Enter fullscreen mode Exit fullscreen mode

In this example, the second then the callback will only be called after the first async operation has completed, and the result of the first operation is passed as an argument to the second then callback.

Promises also have a finally method, which is called whether the Promise resolves or rejects. It is often used for things like cleaning up after an async operation or hiding a loading spinner.

Here’s an example of how you might use the finally method:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('The async operation has completed');
  }, 3000);
});

myPromise
  .then(result => {
    console.log(result);
    return 'This is the next async operation';
  })
  .then(result => console.log(result))
  .catch(error => console.log(error))
  .finally(() => {
    console.log('This code runs regardless of whether the Promise resolves or rejects');
  });
Enter fullscreen mode Exit fullscreen mode

this example, the finally the callback will be called after the Promise has been completed, regardless of whether it resolves or rejects.

It’s worth noting that the finally a method is not called with any arguments, so it cannot access the result of the Promise. If you need to access the result of the Promise, you can use the then method instead.

I hope this helps clarify the use of the JavaScript Promises.

Top comments (0)