Promises

A cleaner way to handle asynchronous results.

Syntaxpromise.then(value => ...).catch(err => ...)

A Promise represents a value that will be available later. It is either pending, fulfilled, or rejected.

Consuming a promise

  • .then() runs when the promise succeeds.
  • .catch() runs if it fails.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Wrap a legacy callback-based API in a Promise to make it chainable with .then().
  • Fetch user data from a REST endpoint and chain a second fetch to get the user's orders.
  • Show a loading spinner before a Promise resolves and hide it in the .finally() handler.

More examples

Create and resolve a Promise

Creates a Promise that resolves after a given millisecond delay, useful for async timing.

Example · js
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
delay(1000).then(() => console.log("1 second passed"));

Chain then and catch

Chains .then calls to parse JSON and extract a name, with .catch handling any network error.

Example · js
fetch("https://jsonplaceholder.typicode.com/users/1")
  .then(res => res.json())
  .then(user => console.log(user.name))
  .catch(err => console.error("Request failed:", err));

Promise with finally

Uses .finally to clear a loading flag regardless of whether the Promise resolved or rejected.

Example · js
let loading = true;
fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then(r => r.json())
  .then(todo => console.log(todo.title))
  .catch(e => console.error(e))
  .finally(() => { loading = false; });

Discussion

  • Be the first to comment on this lesson.
Promises — JavaScript | SoundsCode