Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

JS
JavaScript
0/12 completed
Beginner
What is JavaScript?Variables and data typesOperators and expressionsMaking decisions: if and switchLoops
Intermediate
FunctionsArrays and array methodsObjects
Advanced
Scope and closuresClasses and OOPPromises and async/await
Pro
The event loop
Tracks / JavaScript / Advanced

Promises and async/await

Some work takes time: loading data from an API, reading a file, waiting for a timer. JavaScript doesn't stop and wait. It starts the task, keeps running other code, and handles the result later. This is asynchronous programming.

Callbacks and timers

JavaScript · editable

Notice the order: 3 prints last, even though it appears in the middle of the code.

Promises

A Promise is an object representing a value that will arrive later. It is in one of three states: pending, fulfilled (success) or rejected (error).

JavaScript · editable

async / await

async/await lets you write asynchronous code that reads top-to-bottom like normal code. await pauses only this function until the promise settles.

JavaScript · editable

Use try/catch around await to handle errors. It replaces .catch().

Running tasks in parallel

Awaiting one by one is slow when tasks don't depend on each other. Promise.all runs them together.

JavaScript · editable
Helper Resolves when…
Promise.all All succeed (rejects on the first failure)
Promise.allSettled All finish, success or failure
Promise.race The first one settles
Promise.any The first one succeeds

Real world: fetch

In a browser or Node.js, fetch loads data from an API and returns a promise:

js
async function loadPosts() {
  const res = await fetch('https://api.example.com/posts');
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const posts = await res.json();
  return posts;
}

Always check res.ok. fetch only rejects on network failure, not on 404 or 500 responses.

Practice

Write an async function retry(fn, times) that calls fn() and, if it throws, tries again up to times attempts before giving up. Test it with the flaky function below.

JavaScript · editable
✎ Check your understanding

1.What does an async function always return?

2.You need three independent API calls. What's fastest?

← Classes and OOP