learn2kode.in

What Is a JavaScript Promise?

A Promise in JavaScript represents a value that will be available now, later, or never. It is commonly used to handle asynchronous operations like API calls, file loading, or timers without writing deeply nested callbacks.

Promises help write cleaner, more readable, and maintainable asynchronous code.

Why Promises Are Important

Before Promises, developers used callbacks, which often led to callback hell. Promises solve this by providing a structured way to handle async logic.
Benefits of Promises

Promise States

A JavaScript Promise can be in one of three states:

Once a Promise is fulfilled or rejected, it is settled and cannot change state.

Creating a Promise

const myPromise = new Promise((resolve, reject) => {
  let success = true;

  if (success) {
    resolve("Operation successful");
  } else {
    reject("Operation failed");
  }
});
Using .then() and .catch()
myPromise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });
Promise Chaining
Promises can be chained to perform multiple async tasks in sequence.
fetchData()
  .then(data => processData(data))
  .then(result => saveResult(result))
  .catch(error => console.error(error));
Handling Multiple Promises
Runs multiple promises in parallel and waits for all to finish.
Promise.all([promise1, promise2])
  .then(results => {
    console.log(results);
  })
  .catch(error => console.error(error));

Promises vs Callbacks (Comparison Table)

Feature Callbacks Promises
Readability Low (nested) High (chained)
Error Handling Complex Simple (.catch)
Modern Usage Less Preferred Widely Used
Promises and Async/Await
Promises are the backbone of async/await.
async function getData() {
  try {
    const result = await myPromise;
    console.log(result);
  } catch (error) {
    console.error(error);
  }
}

Common Use Cases of Promises

Best Practices