Promises | Dataplexa

Promises

In real-world applications, many tasks do not finish instantly. Fetching data from a server, reading files, or waiting for a response takes time.

Promises help JavaScript handle these time-based operations in a clean and manageable way.


The Problem Promises Solve

Before promises, JavaScript relied heavily on callbacks. With complex logic, callbacks quickly became hard to read and maintain.

This situation is often called callback hell.


What Is a Promise?

A promise represents a value that will be available now, later, or never.

It acts as a placeholder for a future result.


Promise States

  • Pending – operation is in progress
  • Fulfilled – operation completed successfully
  • Rejected – operation failed

A promise can be settled only once.


Creating a Promise


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

  if (success) {
    resolve("Operation successful");
  } else {
    reject("Operation failed");
  }
});
  

The resolve function signals success, and reject signals failure.


Using a Promise

Promises are consumed using .then() and .catch().


myPromise
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.log(error);
  });
  

This makes asynchronous code easier to follow.


Real-World Example

Simulating a delayed action:


function fetchData() {
  return new Promise(function (resolve) {
    setTimeout(function () {
      resolve("Data loaded");
    }, 2000);
  });
}

fetchData().then(function (data) {
  console.log(data);
});
  

This pattern is common when working with APIs.


Why Promises Are Important

  • Cleaner asynchronous code
  • Better error handling
  • Easier to chain operations

Promises form the foundation of modern async JavaScript.


Common Beginner Mistakes

  • Forgetting to return a promise
  • Not handling errors with .catch()
  • Confusing synchronous and asynchronous flow

Always think in terms of time and execution order.


Thumb Rules

  • Promises handle future values
  • Use .then() for success
  • Use .catch() for errors
  • A promise settles only once

What Comes Next?

Promises are powerful, but they can still feel verbose.

In the next lesson, we will learn async and await, which make asynchronous code even cleaner.