JavaScript Tutorial

Promises, async/await and Modules

Handle asynchronous operations and split modern JavaScript into modules.

Concept

Promises represent a value that may be available later. async/await provides a readable syntax for working with promise-based APIs while preserving asynchronous behavior.

ES modules use export and import to split code into explicit units. This encourages smaller files and clearer dependencies.

Example

async function loadData() {
  const response = await fetch("/api/example");
  if (!response.ok) throw new Error("Request failed");
  return response.json();
}
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.

Practice Tasks

  1. Wrap a timeout in a Promise.
  2. Use try/catch around an awaited operation.
  3. Export one function from a module and import it elsewhere.

Key Takeaways

  • Promises model future results.
  • async/await improves readability but does not make operations synchronous.
  • Modules make dependencies explicit.