Promise in Javascript

Akhil S RAkhil S R
2 min read

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

In simple words :

  • A Promise is like a guarantee that something will be done in the future. It handles tasks that takes time, like loading data from the website. Once the task is done, the Promise either gives you the result (success) or an error (failure)

Promise States

  1. Pending → The task is still in progress.

  2. Fulfilled (Resolved) → The task is completed successfully.

  3. Rejected → The task is failed with an error.

Handling a Promise

To handle the result of the promise, you can use:

  • .then() to handle success (when the Promise is Resolved)

  • .catch() to handle errors (when the Promise is Rejected)

  • .finally() to execute the code after the Promise finishes, regardless of success or failure.

Example

const myPromise = new Promise((resolve, reject) => {
  let success = true;
  if (success) {
    resolve("Task completed successfully!");
  } else {
    reject("Task failed !!!");
  }
});

myPromise
  .then(result => {
    console.log(result); // Runs if resolved
  })
  .catch(error => {
    console.error(error); // Runs if rejected
  })
  .finally(() => {
    console.log("Promise has finished."); // Runs after the .then() or .catch()
  });

Understanding Thenable objects

Promises are thenable objects, meaning they can be chained with .then() to handle asynchronous operations.

Example (with fetch() method.):

fetch('https://api.github.com/users/AkLuffy07')
.then(response => {
    return response.json();
})
.then(data => {
    console.log("GitHub Data :: ", data);
})
.catch(err => console.log(err))
.finally(() => console.log("Fetch method is completed.."))

In the above example, fetch method returns the Promise.

  • So in .then() return the response in the json format.

  • And in the next .then() log the response data. (In the second .then() response is fetched from the first .then() return.)

For more details on the Fetch API, you can refer to this article: Fetch API

Conclusion

  • Promises manages asynchronous operations efficiently.

  • .then() handles the success, .catch() handles the errors, .finally() handles cleanup.

  • Understanding thenables and their chaining is crucial for modern JavaScript development.

17
Subscribe to my newsletter

Read articles from Akhil S R directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Akhil S R
Akhil S R