#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Asynchronous JavaScript

Promises

A promise is a JavaScript object that stands for a value you do not have yet but expect to get later, such as the result of a network request or a timer. Instead of passing a callback into a function, the function hands you back a promise, and you attach what should happen when the work succeeds or fails. Promises are the foundation for fetch, most modern Node.js APIs and the async/await syntax.

The three states of a promise

Every promise is in exactly one of these states:

StateMeaning
pendingThe work has started but has not finished.
fulfilledThe work finished and produced a value.
rejectedThe work failed and produced a reason, usually an Error.

Once a promise is fulfilled or rejected it is called settled, and it never changes again. Calling resolve a second time does nothing. This one-time guarantee is a big improvement over callbacks, which a buggy function might call twice.

Creating and consuming a promise

You create a promise with the Promise constructor. It receives an executor function with two arguments, resolve and reject. Call one of them when the work is done.

function wait(ms) {
  return new Promise((resolve, reject) => {
    if (ms < 0) {
      reject(new Error('Delay cannot be negative'));
      return;
    }
    setTimeout(() => resolve(`Waited ${ms} ms`), ms);
  });
}

wait(500)
  .then((message) => {
    console.log(message);
    return wait(300);          // returning a promise chains it
  })
  .then((message) => console.log(message))
  .catch((error) => console.error('Failed:', error.message))
  .finally(() => console.log('Done either way'));

.then() runs when the promise is fulfilled. Whatever you return from it becomes the value for the next .then(). If you return another promise, the chain waits for it. .catch() handles a rejection from any earlier step, and .finally() runs in both cases, which is handy for hiding a loading spinner.

Why chaining keeps code flat

With callbacks, each dependent step sits inside the previous one. With promises, each step is a new link at the same indentation level. A single .catch() at the end covers errors thrown anywhere above it, including a normal throw inside a .then() handler. That is the main reason promises replaced deep callback nesting.

Running several promises together

  • Promise.all([...]) waits for every promise and rejects as soon as one fails.
  • Promise.allSettled([...]) waits for all of them and reports each result, success or failure.
  • Promise.race([...]) settles with whichever promise settles first, useful for timeouts.
  • Promise.any([...]) fulfills with the first success and only rejects if all fail.

Common mistake: forgetting to return

Inside a .then(), if you start another asynchronous task but do not return its promise, the chain will not wait for it. The next step runs too early, and any error from that task escapes your .catch(). A second frequent slip is leaving a chain without any .catch(); in Node.js an unhandled rejection can stop the process. Finally, avoid wrapping a function that already returns a promise inside new Promise; just return the existing promise.

What to remember

A promise is a placeholder for a future result that settles once. Use .then() for success, return values or promises to pass data along, end chains with .catch(), and use the Promise.all family when tasks can run at the same time.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course