JavaScript Promises

Handle future results with then and catch.

✍️ 3 exercises + code challenge in this lesson

A Promise represents a value that will be available in the future, like the result of a network request.

A promise is in one of three states: pending, fulfilled (success) or rejected (error).

  • .then(result => ...): runs when it succeeds.
  • .catch(error => ...): runs when it fails.
  • .finally(): runs either way.
  • Promise.all([...]): waits for several promises.

Key Takeaways: JavaScript Promises

Mastering JavaScript Promises helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

JavaScript Promises Code Example

JavaScript
<pre id="out"></pre>
<script>
const log = (...a) => document.getElementById("out").textContent += a.join(" ") + "\n";
function orderPizza(flavour) {
  return new Promise((resolve, reject) => {
    log("Ordering", flavour, "...");
    setTimeout(() => {
      if (flavour === "pineapple") reject(new Error("Out of pineapple!"));
      else resolve(`${flavour} pizza is ready 🍕`);
    }, 1000);
  });
}

orderPizza("tikka")
  .then(msg => log(msg))
  .then(() => orderPizza("pineapple"))
  .then(msg => log(msg))
  .catch(err => log("Problem:", err.message))
  .finally(() => log("Done ordering."));
</script>
Free sign-in required · Google login available

JavaScript Promises Practice Exercises

Check what you learned in “JavaScript Promises”.

/ 3 solved
Fill in the blank

Handle the successful result of a promise.

fetchData().(data => log(data));
✓ Correct! Not quite. Try again.
Multiple choice

Which method handles a rejected promise?

✓ Correct! Not quite. Try again.
Code challenge

Create a promise that resolves with "Ready" and log the value with then().

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services