Skip to content
techsnow

Async JavaScript

Async/Await and Fetch

async/await lets you write asynchronous code that reads like normal, top-to-bottom code. fetch loads data from a server.

async function loadUser(id) {
  try {
    const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const user = await response.json();
    console.log(user.name, "-", user.email);
  } catch (error) {
    console.error("Could not load user:", error.message);
  }
}

loadUser(1);

Output

Leanne Graham - Sincere@april.biz
  • await can only be used inside an async function (or at the top level of a module).
  • fetch does not throw on 404 or 500, so always check response.ok.

Sending data

await fetch("/api/messages", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ text: "Hello!" }),
});