Skip to main content

Command Palette

Search for a command to run...

JavaScript Promises Explained for Beginners

Updated
2 min read
JavaScript Promises Explained for Beginners

In JavaScript, many tasks take time, like:

  • Fetching data from an API

  • Reading files

  • Waiting for a timer

Earlier, developers used callbacks to handle these tasks. But callbacks often made the code messy and hard to read.

To solve this problem, Promises were introduced.

What Problem Promises Solve

Before Promises, developers used callbacks like this:

getData(function(data) {
  processData(data, function(result) {
    saveData(result, function() {
      console.log("Done");
    });
  });
});

This is called callback hell

  • Too many nested functions

  • Hard to read

  • Difficult to debug

Promises solve this by:

  • Making code cleaner

  • Improving readability

  • Handling async operations better

What is a Promise?

A Promise is an object that represents a piece of code or something else will complete in the future

Example:

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

  if (success) {
    resolve("Task completed");
  } else {
    reject("Task failed");
  }
});

Promise States

A Promise has 3 states:

  1. Pending → Initial state (waiting)

  2. Fulfilled → Task completed successfully

  3. Rejected → Task failed

Promise Lifecycle

Pending 
   ↓ 
Fulfilled(resolve) 
   OR 
Rejected(reject)

Once completed, the state cannot change.


Handling Success and Failure

We use .then() and .catch() to handle results.

promise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.log(error);
  });

.then() → handles success

.catch() → handles error

Example using setTimeout

function delayTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Task finished");
    }, 2000);
  });
}

delayTask()
  .then(result => console.log(result))
  .catch(err => console.log(err));

Output:

Output after 2 seconds: Task finished

Promise Chaining Concept

Promises can be chained to handle multiple steps.

fetchData()
  .then(data => {
    return processData(data);
  })
  .then(result => {
    return saveData(result);
  })
  .then(() => {
    console.log("All done");
  })
  .catch(err => console.log(err));

Each .then() passes data to the next step.

Promises Improve Readability

  • Avoid nested callbacks

  • Clear step-by-step flow

  • Easy error handling

  • Better structure

Code becomes more understandable

Conclusion

Promises are a powerful feature in JavaScript that helps to manage asynchronous operations in a clean and readable way. They solve the problem of callback hell and make code cleaner and easier to maintain.

Promises gives you results when the task is completed without blocking your program.