Promises in JavaScript

Promises in JavaScript

Recently I've been reading up on Asynchronous programming in JavaScript, which is a powerful tool for building responsive and efficient applications. However, it can be challenging to manage the complexity of asynchronous tasks, especially when they involve multiple operations that need to be performed in a specific order, and to resolve this is where promises come in. Promises are a solution to this problem, they provide a more structured and readable way to handle asynchronous operations.

via GIPHY

What are Promises?

At their core, promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They are a powerful tool for handling asynchronous operations in JavaScript. They become essential when waiting for some asynchronous operation to run without holding back the execution of the rest of the code.

For example, when ordering food at some restaurants. When we pay, we get a ticket with an order number. Then, when that number is called, we can go and get our food. That ticket they gave us is our promise, which tells us that we will eventually get our food, but that we don’t have it yet. When they call that number to go get the food, it means that the promise is complete. But it turns out that a promise can be completed correctly or a mistake can occur. For example, it may happen that the restaurant does not have the food we ordered, so when they call us with our number, two things may happen:

  1. Our order is resolved, and we get the food.

  2. Our order is rejected, and we get a reason why.

Promises have three states: pending, fulfilled, and rejected.

  • Pending: This is the initial state of a promise. It means that the promise is neither fulfilled nor rejected yet. It’s waiting.

  • Fulfilled: This state means that the promise has been resolved successfully, and the result is available. The promise’s then method is called with the resolved value as its argument.

  • Rejected: This state means that the promise has been rejected, and the reason for rejection is available.

These 3 states help in handling asynchronous tasks more effectively by allowing us to associate handlers with an asynchronous action’s eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods. Instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

How to Create a Promise in JavaScript

To create a promise, you can use the Promise constructor and its syntax. A basic promise can be created by following these steps:

  1. Create a new promise object using the Promise constructor.

  2. Define the asynchronous operation that the promise represents.

  3. Call the resolve function to fulfill the promise or the reject function to reject it.

A common use case for promises includes fetching data from APIs. Here’s an example of creating a promise to fetch data from an API asynchronously:

const promise = new Promise((resolve, reject) => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => resolve(data))
    .catch(error => reject(error));
});

Code Explanation

  • This code creates a new promise object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

  • The promise is created using the Promise constructor, which takes a function as its argument. This function takes two parameters: resolve and reject.

  • The fetch function is used to make an asynchronous request to the specified URL.

  • The then method is called on the response object returned by fetch, which returns a new promise that resolves to the JSON data returned by the server.

  • The resolve function is called with this data as its argument, which fulfills the promise.

  • If an error occurs during the request, the catch method is called, which calls the reject function with the error as its argument, which rejects the promise.

Conclusion

Promises are a powerful tool for handling asynchronous operations in JavaScript. They provide a more structured and readable way to manage the complexity of asynchronous tasks. By understanding the basics of promises, we can write more efficient and maintainable code.