← Back to Course

⏳ Async/Await and Promises

Some work finishes later, such as reading data, waiting on a server, or loading a file. Promises and async functions help you manage that delayed work clearly.

What a Promise Represents

A promise represents a result that is not ready yet. It may resolve later with a value or reject with an error.

Example: Async Function

async function getMessage(): Promise<string> {
  return "Loaded data";
}

getMessage().then((message) => {
  console.log(message);
});

Using Await

Example: Wait for a Result

async function run(): Promise<void> {
  const message = await getMessage();
  console.log(message);
}

run();

🎯 Key Ideas

  • Use async on functions that use await
  • await pauses inside that function until the promise resolves
  • Wrap async work in try and catch when failure is possible
← Back to Code Foundations