Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP W3.CSS C C++ C# HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

JS Tutorial

JS Home JS Introduction JS Where To JS Output JS Syntax JS Operators JS If Conditions JS Loops JS Strings JS Numbers JS Functions JS Objects JS Scope JS Dates JS Temporal  New JS Arrays JS Sets JS Maps JS Iterations JS Math JS RegExp JS Data Types JS Errors JS Debugging JS Style Guide JS Reference JS Projects  New JS Versions JS HTML DOM JS HTML Events JS HTML First

JS Advanced

JS Functions JS Objects JS Classes JS Asynchronous JS Modules JS Meta & Proxy JS Typed Arrays JS DOM Navigation JS Windows JS Web API JS AJAX JS JSON JS jQuery JS Graphics JS Examples JS Reference


JavaScript Promises

"I Promise a Result!"

A Promise represents the completion or failure of an asynchronous operation.

A Promise can be in one of 3 exclusive states:

pendingoperation started (not finished)
rejectedoperation failed
fulfilledoperation completed

JavaScript Promises were created to make asynchronous JavaScript easier to use.

JavaScript Promises

A Promise represents the eventual result of an asynchronous operation.

It acts as a placeholder for a value that is not available yet.

Instead of waiting for the operation to finish, JavaScript continues running other code.

When the operation completes, the Promise is either fulfilled with a value or rejected with an error.


Why Promises?

Callbacks work well for simple asynchronous tasks.

However, when several asynchronous operations depend on each other, callbacks can become deeply nested.

Promises provide a cleaner and more readable way to organize asynchronous code.

Example

step1(function(result1) {
  step2(result1, function(result2) {
    step3(result2, function(result3) {
      display(result3);
    });
  });
});

The style above is often called callback hell.

Promises let you write the same logic in a cleaner way.


Same Flow with Promises

Example

step1()
  .then(step2)
  .then(step3)
  .then(display);

Each then() waits for the previous Promise to finish.

The code is flatter and easier to read.


Promise States

A Promise acts as a placeholder for a value that will be available at some point in the future, allowing you to handle asynchronous code in a cleaner way than traditional callbacks.

Every Promise is always in one of three states.

State Description
Pending The operation is still running.
Fulfilled The operation completed successfully.
Rejected The operation failed.
Pending
   │
   ├────────► Fulfilled
   │
   └────────► Rejected

Pending

The initial state. The operation has started but is neither fulfilled nor rejected.

Fulfilled

The operation has completed successfully, and a value is available.

Rejected

The operation has failed, and a reason (error) is available.

Settled

A promise is considered settled if it is fulfilled or rejected (not pending).


The then() Method

The then() method runs when a Promise is fulfilled.

Example

fetch("demo.txt")
.then(function(response) {
  return response.text();
})
.then(function(text) {
  document.getElementById("demo").innerHTML = text;
});

The first then() receives the fetch response.

The second then() receives the text returned by the first.


The catch() Method

If a Promise is rejected, catch() handles the error.

Example

fetch("missing.txt")
.then(function(response) {
  return response.text();
})
.catch(function(error) {
  console.log(error);
});

The finally() Method

The finally() method runs whether the Promise succeeds or fails.

Example

fetch("demo.txt")
.then(...)
.catch(...)
.finally(function() {
  console.log("Finished");
});

Creating a Promise

Most of the time you will use Promises returned by JavaScript APIs.

You can also create your own Promise.

Syntax

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

// Code that may take some time

  resolve(value); // when successful
  reject(value);  // when error
});

The promise constructor takes a function with two parameters.

ParameterDescription
resolvefunction to run if finishes successfully
rejectfunction to run if finishes with an error

Example

const myPromise = new Promise(function(resolve, reject) {

// Code that may take some time

  let success = true;
  if (success) {
    resolve("Done");
  } else {
    reject("Failed");
  }

});

Call resolve() when the operation succeeds.

Call reject() when it fails.


Summary

  • A Promise represents the future result of an asynchronous operation.
  • A Promise can be pending, fulfilled, or rejected.
  • Use then() to handle successful results.
  • Use catch() to handle errors.
  • Use finally() to run cleanup code.
  • Promises make asynchronous code easier to read than nested callbacks.

Promises How To

Here is how to use a Promise:

Example

myPromise.then(
  function(value) { /* code if success */ },
  function(value) { /* code if error */ }
);

then() takes two arguments, one callback function for success and another for failure.

Both are optional, so you can add a callback function for success or failure only.

Examples

// Create a Promise Object
let myPromise = new Promise(function(resolve, reject) {
  ok = true;

// Code that may take some time

  if (ok) {
    resolve("OK");
  } else {
    reject("Error");
  }
});

// Using then() to display the result
myPromise.then(
  function(value) {myDisplayer(value);},
  function(value) {myDisplayer(value);}
);

Try it Yourself »

// Create a Promise Object
let myPromise = new Promise(function(resolve, reject) {
  ok = false;

// Code that may take some time

  if (ok) {
    resolve("OK");
  } else {
    reject("Error");
  }
});

// Using then() to display the result
myPromise.then(
  function(value) {myDisplayer(value);},
  function(value) {myDisplayer(value);}
);

Try it Yourself »

A promise represents a value that will be available later.

A promise is a container for a future result.

The result can be a value or an error.


The JavaScript Promise Object

A Promise contains both the producing code and calls to the consuming code:

Promise Syntax

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

// "Producing Code" (May take some time)

  resolve(value); // when successful
  reject(value);  // when error
});

// "Consuming Code" (Must wait for a fulfilled Promise)
myPromise.then(
  function(value) { /* code if success */ },
  function(value) { /* code if error */ }
);

When the producing code obtains the result, it should call one of the two callbacks:

WhenCall
Successresolve(value)
Errorreject(value)

A promise can resolve or reject only once.


Promise Object Properties

A JavaScript Promise object can be:

  • Pending
  • Fulfilled
  • Rejected

The Promise object supports two properties: state and result.

While a Promise object is "pending" (working), the result is undefined.

When a Promise object is "fulfilled", the result is a value.

When a Promise object is "rejected", the result is an error object.

myPromise.statemyPromise.result
"pending"undefined
"fulfilled"a result value
"rejected"an error object

You cannot access the Promise properties state and result.

You must use a Promise method to handle promises.


Core Methods and Usage

Promises are consumed using methods attached to the promise object:

  • .then(onFulfilled, onRejected):
    This method attaches handlers for both the fulfillment and rejection cases. It returns a new promise, which enables method chaining.

  • .catch(onRejected):
    This is a shorthand for .then(null, onRejected) and is typically used to handle errors at the end of a promise chain.

  • .finally(onFinally):
    This handler is called when the promise is settled (either fulfilled or rejected), regardless of the outcome. It's useful for cleanup operations.

Using then and catch

You do not read a promise result immediately.

You attach code that runs when the promise finishes.

then() runs when a promise is fulfilled.

catch() runs when a promise is rejected.

Examples

let promise = Promise.resolve("OK");

promise
.then(function(value) {
  console.log(value);
})
.catch(function(value) {
  myDisplayer(value);
});

Try it Yourself »

let promise = Promise.reject("Error");

promise
.then(function(value) {
  console.log(value);
})
.catch(function(value) {
  myDisplayer(value);
});

Try it Yourself »

When a promise is fulfilled, the then() function runs.


Returning a Promise

Promises become powerful when you return a promise from then().

This creates a clean chain.

Example

// Three functions to run in steps
function step1() {
  return Promise.resolve("A");
}
function step2(value) {
  return Promise.resolve(value + "B");
}
function step3(value) {
  return Promise.resolve(value + "C");
}

// Run the three functions in steps
step1()
.then(function(value) {
  return step2(value);
})
.then(function(value) {
  return step3(value);
})
.then(function(value) {
  myDisplayer(value);
});

Try it Yourself »

The chain runs step by step as each promise finishes.


Where to Put catch

You can handle errors at the end of the chain.

A single catch() can catch errors from any step above.

Example

step1()
.then(function(value) {
  return step2(value);
})
.then(function(value) {
  return step3(value);
})
.catch(function(error) {
  console.log(error);
});

This is one reason promises are easier than many nested callbacks.


Common Beginner Mistakes

Forgetting to return a promise breaks the chain.

Example

step1()
.then(function(value) {
  step2(value);
})
.then(function(value) {
  console.log(value);
});

The second then() runs too early.

It runs because nothing was returned from the first then().

If you start an async step in then(), return it.


Promises and Real JavaScript

Many web APIs return promises.

fetch() is a common example.

Example

fetch("data.json")
.then(function(response) {
  return response.json();
})
.then(function(data) {
  console.log(data);
})
.catch(function(error) {
  console.log(error);
});

This is promise-based async programming.



Promise API Static Methods

JavaScript also provides static methods on the Promise object for handling multiple promises at once:

  • Promise.all(iterable):
    Fulfills when all promises in the iterable are fulfilled; rejects immediately if any promise rejects.

  • Promise.allSettled(iterable):
    Waits for all promises to settle (either fulfill or reject) and returns an array of their results.

  • Promise.race(iterable):
    Settles (fulfills or rejects) as soon as any of the promises in the iterable settles.

  • Promise.any(iterable):
    Fulfills as soon as any promise in the iterable fulfills; rejects if all promises reject.


JavaScript Promise vs Callback

To demonstrate the use of promises, we will use the callback examples from the previous chapter:

  • Waiting for a Timeout
  • Waiting for a File

Waiting for a Timeout

Example Using Callback

setTimeout(function() { myFunction("I love You !!!"); }, 3000);

function myFunction(value) {
  document.getElementById("demo").innerHTML = value;
}

Try it Yourself »

Example Using Promise

let myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve("I love You !!"); }, 3000);
});

myPromise.then(function(value) {
  document.getElementById("demo").innerHTML = value;
});

Try it Yourself »


Waiting for a file

Example using Callback

function getFile(myCallback) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myCallback(req.responseText);
    } else {
      myCallback("Error: " + req.status);
    }
  }
  req.send();
}

getFile(myDisplayer);

Try it Yourself »

Example using Promise

let myPromise = new Promise(function(myResolve, myReject) {
  let req = new XMLHttpRequest();
  req.open('GET', "mycar.html");
  req.onload = function() {
    if (req.status == 200) {
      myResolve(req.response);
    } else {
      myReject("File not Found");
    }
  };
  req.send();
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);

Try it Yourself »


More Examples

Basic Syntax

async function myDisplay() {
  let myPromise = new Promise(function(resolve, reject) {
    resolve("I love You !!");
  });
  document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

Try it Yourself »

The two arguments (resolve and reject) are pre-defined by JavaScript.

We will not create them, but call one of them when the executor function is ready.

Very often we will not need a reject function.

Example without reject

async function myDisplay() {
  let myPromise = new Promise(function(resolve) {
    resolve("I love You !!");
  });
  document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

Try it Yourself »

Waiting for a Timeout

async function myDisplay() {
  let myPromise = new Promise(function(resolve) {
    setTimeout(function() {resolve("I love You !!");}, 3000);
  });
  document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();

Try it Yourself »


Note

Promises provide a cleaner way to work with asynchronous operations than nested callbacks.

In the next chapter, you will learn how async/await make Promise-based code look even more like ordinary synchronous JavaScript.


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

-->