đŸ”„Promises in JavascriptđŸ”„

·

4 min read

Table of contents

No heading

No headings in the article.

A Promise in JavaScript is a representation of a value that may not be available yet but will be resolved in the future. A Promise has three possible states: Pending, Fulfilled and Rejected. A Promise starts in a Pending state and will either be Fulfilled with a value, or Rejected with an error message

A Promise has these states:

  • pending: initial state, neither fulfilled nor rejected.

  • fulfilled: meaning that the operation was completed successfully.

  • rejected: meaning that the operation is failed.

The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error).

When you create a Promise, you pass in a function with two arguments: resolve and reject. The resolve function is called when the Promise is fulfilled with a value, and the reject function is called when the Promise is rejected with an error.

Here’s an example of creating a Promise that resolves after a certain amount of time:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Success!");
  }, 1000);
});

In this example, we create a new Promise that resolves after 1 second with the value “Success!”.

Let’s understand with a simple Promise Example:

We are defining a promise by calling the Promise class and constructing an object with two parameters resolveand rejectlike this:

const myPromise = new Promise((resolve, reject) => {
  let a = true;
  setTimeout(() => {
    return (a)? resolve('first method') : reject('rejected');
  }, 3000);
});

console.log(myPromise); //We are printing the mypromise in the console.

When we try to execute the above code in the console, we will be getting state as pending.

Once 3 sec is completed then if it is resolved, it will show the status as fulfilled or if it is rejected then it will show the status as rejected .

We can also use the built-in Promise API to achieve the same thing.

const anotherPromise = Promise.resolve("Second Method")

console.log(anotherPromise);

JavaScript promises are a very powerful feature that help you run asynchronous code in JavaScript and also helps us in avoiding callback hell.

Promises are a powerful feature in JavaScript that allows us to manage asynchronous code more elegantly and easily. In this article, we’ll explore the concept of JavaScript Promises and how to use them to improve your code.

Promise Chaining:

Promise Chaining is a technique that allows you to execute multiple asynchronous operations in a sequence. When a Promise is resolved, you can chain another Promise to it using the then() method. The then() method takes two arguments: a function to be executed when the Promise is resolved, and a function to be executed when the Promise is rejected.

Here’s an example of Promise Chaining:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(10);
  }, 1000);
});

myPromise.then((result) => {
  console.log(result); // Output: 10
  return result * 2;
}).then((result) => {
  console.log(result); // Output: 20
}).catch((err) => {
  console.log(err);
});

In this example, we create a Promise that resolves after 1 second with the value 10. We then chain another Promise to it using the then() method, which multiplies the result by 2. Finally, we use the catch() method to catch any errors that may occur.

Error Handling:

When using Promises, it’s important to handle errors properly. You can handle errors using the catch() method, which is called when a Promise is rejected. You can also chain multiple catch() methods to handle different types of errors.

Here’s an example of error handling using the catch() method:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("Error!");
  }, 1000);
});

myPromise.then((result) => {
  console.log(result);
}).catch((err) => {
  console.log(err); // Output: Error!
});

In this example, we create a Promise that rejects after 1 second with the error message “Error!”. We then use the catch() method to catch the error and log it to the console.

Conclusion:

JavaScript Promises are a powerful feature that can help you manage asynchronous code in a more elegant and manageable way. By using Promise Chaining and Error Handling, you can create complex asynchronous code that is easy to read and maintain. With a little practice, you can become proficient in using Promises to improve your JavaScript code.

Thanks for reading📖! I hope you all enjoyed😀 reading this article.

Keep smiling!

Have a nice day!

Did you find this article valuable?

Support Hemanth Raju by becoming a sponsor. Any amount is appreciated!

Â