In JavaScript, a Promise is an object that represents a value that may not be available yet, but will be resolved in the future. Promises are used to handle asynchronous operations, such as making network requests or accessing a database, where the result is not immediately available.
I’d like to kick off our adventure, if you’re ready..
How Promises Work?
A promise is a proxy for a value that is not necessarily known at the time the promise is created. This allows you to attach handlers to the final success value or failure reason of an asynchronous action. This allows asynchronous methods to return values like synchronous methods: instead of returning the final value immediately, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise has three possible states:
- Pending: The initial state of a promise. The promise was neither fulfilled nor rejected.
- Fulfilled: The promise is resolved and the resulting value is available.
- Rejected: The promise has been rejected and an error has occurred.
Once a promise is set, it cannot be set again. The resolve() or reject() functions can only be called once, and any subsequent calls to these functions will have no effect. The immutability of a fixed promise is an important feature because it ensures that the value of the promise remains consistent and predictable.
Once a promise is fixed, its value cannot be changed, which helps prevent unexpected behavior and makes the code easier to reason about.
How to Create Promises?
A Promise is created using the Promise
constructor, which takes a single argument, a function called executor. The executor function takes two arguments: resolve
and reject
. These are functions that are called when the promise is fulfilled or rejected.
To show you what I mean..
In the above example the promise will be resolved after one second, and the value of the resolved
promise will be the users array.
Once the promise is created, you can use the then
method to attach a callback function that will be called when the promise is fulfilled. The then
method takes two arguments: a callback function for the resolved
value and a callback function for the rejected
value.
To show you what I mean..
Moving forward on our adventure, let’s take a look at an example of a Promise that has been rejected.
To show you what I mean..
Chained Promises
The methods below are used to associate a forward action with the settlement of a promise. Since these methods return promises, they can be chained:
Promise.prototype.then()
Promise.prototype.catch()
Promise.prototype.finally()
Chaining of promises in JavaScript involves creating a sequence of promises that are executed one after the other. Each promise in the chain depends on the successful completion of the previous promise, so if any promise in the chain fails, the entire chain fails.
Let’s see how we can chain promises in JavaScript:
Here, fetchData()
function is used to fetch data from remote API and perform some operations on it. The FetchData()
function returns a promise that resolves with the result of the operation.
The promise chain starts by fetching user data from the API, then uses the ID of the first user to fetch their posts, and finally fetches the comments for that post using the ID of the first post. Each then()
method in the chain handles the resolved value of the previous promise and the last catch()
method handles any errors that occur during the chain.
We can create multiple chains with the then()
method as per the requirements. Like synchronous code, chaining will result in a sequence that will run sequentially. Let us see a simple example..
Benefits of Promises
Promises offer several advantages over the traditional callback based approach to handling asynchronous operations in JavaScript. Some of the key benefits include:
- Better readability: Promises allow you to write code that is more readable and easier to understand than traditional callback-based methods. With Promises, you can chain together asynchronous operations in a sequence that makes it clear in which order the operations are to be executed.
- Improved error handling: Promises make it easier to handle errors that may occur during asynchronous operations. With Promises, you can use the catch method to handle errors that occur during any step in the chain, instead of handling errors separately for each step.
- Avoiding callback hell: Promises can help you avoid “callback hell”, a situation where you have a series of nested callbacks that can be difficult to manage and debug. With promises, you can chain together asynchronous operations without involving multiple levels of callbacks.
- Ability to return a value: Promises allow you to return a value from an asynchronous operation, making it easy to pass the result of one operation to another in sequence. This is especially useful when you need to perform multiple asynchronous operations in sequence and the result of each operation needs to be used in the next operation.
- Better compatibility: Promises are a standardized feature in modern JavaScript, and are supported by all modern browsers and Node.js. This means that Promises can be used in different environments without the need for separate code for each.
How Do I Cancel a Promise?
In modern JavaScript – no, once a promise is created you cannot undelete it. It will execute its code and either resolve or reject, and there is no built-in way to cancel the operation.
There are a few techniques you can use to simulate cancellation:
- Timeout: You can use a timeout to reject the promise if it takes too long to resolve. This technique is useful if you are making network requests and want to limit the time it takes.
- Aborting a network request: You can use the abort controller to abort the network request. The Fetch API provides an
AbortController
API that allows you to abort a network request before it has completed. - Using a flag: You can use a flag in your code to simulate cancellation. You can set a flag to true to indicate that the operation should be canceled, and then check the flag in your promise code to determine whether to continue or reject the promise.
It’s worth noting that none of these techniques actually cancel a promise; They quickly reject it. If you need real cancellation, you may need to use a library that provides cancellation support, such as rxjs or bluebird.
Bluebird Promise Cancellation
Bluebird is a popular Promise library for JavaScript that provides advanced features, including Promise cancellation. Promise cancellation is the ability to cancel a Promise, which is useful for canceling ongoing or long running asynchronous operations.
With the help of Bluebird, Promise cancellation is achieved using the Promise.cancel()
method. This method is not part of the standard Promise API and is specific to Bluebird.
To use Promise cancellation in Bluebird, you need to create a cancellable Promise using the new Promise()
constructor and passing a cancel function as an argument. The cancel function will be called when the Promise is canceled.
Multiple Promises in Parallel
With the help of Promises, it’s easier to manage and execute multiple asynchronous operations in parallel and wait for all of them to complete before continuing.
To show you what I mean..
Four promises are created using the new Promise()
syntax. Each promise is resolved or rejected after a certain timeout period using setTimeout()
method. The error
function is defined to log any error to the console.
After creating above promises, now we will see instances of using different Promise methods.
Promise.all() method
Below instance uses Promise.all()
method which takes an array of promises and waits for all promises to be fulfilled. Once all the promises are resolved, then()
method is executed which returns an array of values in the order they were passed in the promise array. In this case, all three promises are resolved and their values are logged to the console.
This is great way to, e.g. fetch data using two different requests, and then combine them once both requests complete.
Promise.any() method
Below instance uses Promise.any()
method which takes an array of promises and waits for any one of them to be fulfilled. Once the first promise is resolved, then()
method is executed which returns the resolved value of the first promise. In this case, the third promise is resolved before the other two and its value is logged to the console.
Promise.race() method
Below instance uses Promise.race()
method which takes an array of promises and waits for the first promise to be either resolved or rejected. Once the first promise is settled, then()
method is executed which returns the resolved or rejected value of the first settled promise. In this case, the third promise is resolved before the other two, so its value is logged to the console.
Promise.allSettled() method
Below instance uses Promise.allSettled()
method which takes an array of promises and waits for all promises to be settled, i.e., either resolved or rejected. Once all promises are settled, then()
method is executed which returns an array of objects, each object containing the status and value or reason of each promise. In this case, all promises are settled, so the status and values or reasons of all promises are logged to the console.
As in ending
The Fetch API is a modern replacement for the older XMLHttpRequest
object, and is based on promises. When you make a request with the Fetch API, you get back a promise that resolves to a response object. This allows you to use the then()
method to handle the response in a clean and readable way.
Async functions are a new addition to JavaScript, and they are built on top of promises. Async functions allow you to write asynchronous code that looks like synchronous code, making it easier to read and write. Async functions use the wait keyword to wait for promises to resolve before continuing, making it possible to write asynchronous code that looks like a sequence of synchronous statements.
In both of these idioms, promises are used to handle asynchronous operations in a clean and readable manner. By using Promises, you can avoid callback hell and write asynchronous code that is easier to reason about.
🍀Support
Please consider following and supporting us by subscribing to our channel. Your support is greatly appreciated and will help us continue creating content for you to enjoy. Thank you in advance for your support!!!