JavaScript lesson · 18 min

JavaScript Promises

Represent work that finishes later and handle the result with then and catch.

Code runs locally in your browser

What you will practice

  • Understand a Promise as a future result.
  • Resolve a Promise after delayed work.
  • Handle success and failure paths.

What this means

A Promise represents a result that is not ready yet. The work may finish successfully, or it may fail.

A pending Promise is still working. A fulfilled Promise has a successful value. A rejected Promise has an error.

`then` runs when the Promise succeeds. `catch` runs when it fails.

If this is your first time seeing this

A Promise is JavaScript's way to talk about work that finishes later.

You write what should happen after success or after failure, instead of pretending the value is available immediately.

Mini glossary

Promise
An object representing a future success or failure.
resolve
Finish a Promise successfully with a value.
reject
Finish a Promise with an error.

Example from everyday life

A Promise is like ordering food. You do not have the meal yet, but you have a receipt. Later, the order is either fulfilled and you receive food, or rejected because something went wrong.

How it works step by step

  1. The code creates a `loadProfile` function that returns a Promise.
  2. Inside the Promise, `setTimeout` simulates work that finishes a little later.
  3. When the timeout finishes, `resolve` sends back a profile object.
  4. The code returns the Promise chain so the lesson runner waits for the final log.

Where you will use this

  • Browser APIs return Promises when reading files, making requests, or waiting for permissions.
  • A UI can show loading state while a Promise is pending.
  • A tool can run validation after a delayed operation and then show the result.

Before you run the code

Promises are the foundation of modern asynchronous JavaScript.

At first, think of them as a container for a future value. The value is not available immediately, so your code describes what should happen when it arrives.

Common beginner mistakes

  • Trying to use the result before the Promise resolves.
  • Forgetting to return the Promise chain from a function.
  • Handling success but forgetting the failure path.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingWaits for the future profile result
WaitingReads data from the resolved value

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change the delay from `120` to `500` and watch the output wait.
  • Change the resolved plan from `Pro` to `Free`.
  • Replace `resolve` with `reject(new Error("Offline"))` and watch catch run.