Member-only story
Promises are an essential concept in modern JavaScript programming. They allow us to handle asynchronous operations more efficiently by providing a way to manage callbacks and avoid callback hell. At their core, promises have three distinct states: pending, fulfilled, and rejected. Let’s dive deeper into each state and explore how they work with practical code examples.
Pending State
A promise is initially created in the pending state. It represents an operation that has not yet completed or failed. During this time, it can transition to either the fulfilled or rejected state. Here’s an example of creating a new promise in the pending state:
const myPromise = new Promise((resolve, reject) => {
// Simulate async operation
setTimeout(() => resolve('Hello World'), 2000);
});
console.log(myPromise); // Output: Promise <pending>
In this example, we create a new promise using the Promise()
constructor. The function passed to the constructor acts as the executor and runs immediately when the promise is instantiated. We simulate an asynchronous…