Skip to main content

JavaScript Asynchronous

JavaScript Promises

Written by Published

A promise is an object representing a value that is not ready yet.

Instead of passing a callback in, you get an object back and attach handlers to it.

That small change is what lets asynchronous code be chained rather than nested.

Example

Example

javascript

const promise = new Promise(function (resolve) {
  setTimeout(function () {
    resolve("Ada");
  }, 10);
});

promise.then(function (name) {
  console.log("got " + name);
});

The output is got Ada.

The Three States

Pending - the work has not finished.

Fulfilled - it finished and produced a value.

Rejected - it failed and produced a reason.

Syntax

Syntax

javascript

const promise = new Promise(function (resolve, reject) {
  // call resolve(value) or reject(reason)
});

promise.then(handler);

Once settled, a promise never changes state again.

Creating a Promise

The function you pass runs immediately.

It receives resolve and reject to report the outcome.

Example

Example

javascript

const promise = new Promise(function (resolve, reject) {
  const ok = true;
  if (ok) {
    resolve("worked");
  } else {
    reject("failed");
  }
});

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

The output is worked.

Handling a Rejection

catch receives the reason a promise was rejected.

Example

Example

javascript

const promise = new Promise(function (resolve, reject) {
  reject("no network");
});

promise.catch(function (reason) {
  console.log("failed: " + reason);
});

The output is failed: no network.

Ready-Made Promises

Promise.resolve and Promise.reject settle immediately.

Example

Example

javascript

Promise.resolve("here").then(function (value) {
  console.log(value);
});

Promise.reject("gone").catch(function (reason) {
  console.log(reason);
});

These are handy for testing and for returning a value that is already known.

It Settles Only Once

The second call is ignored entirely.

A promise has one outcome and keeps it.

Example

Example

javascript

const promise = new Promise(function (resolve) {
  resolve("first");
  resolve("second");
});

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

The output is first.

then Always Runs Later

Even an already-resolved promise calls its handler after the current code.

This keeps the order predictable.

Example

Example

javascript

console.log("first");

Promise.resolve().then(function () {
  console.log("third");
});

console.log("second");

The output is first, second, third.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Promises</title>
</head>
<body>

  <h1>Promises</h1>

  <p id="out">Loading...</p>

  <script>
    function loadUser() {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve("Ada Lovelace");
        }, 1000);
      });
    }

    loadUser()
      .then(function (name) {
        document.getElementById("out").textContent = "Welcome, " + name;
      })
      .catch(function (reason) {
        document.getElementById("out").textContent = "Failed: " + reason;
      });
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try rejecting:

Swap resolve for reject("no network") and watch the catch run.

Important Points

  • A promise represents a value that is not ready yet.
  • It is pending, then either fulfilled or rejected.
  • then handles success and catch handles failure.
  • A promise settles only once.
  • Handlers always run after the current code has finished.

Conclusion

Promises replace the callback argument with an object you can pass around.

That makes asynchronous work composable in a way callbacks never were.

The next lesson uses that to flatten nested work into a chain.