Labs ICT
๐ŸŽ“ SIWES/IT Login

Async & Await

1 min read | JavaScript Tutorial
๐ŸŽ“

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

async Functions

The async keyword turns any function into one that returns a Promise. Inside, you can use await to pause execution until a promise settles.

async function getData() {
  return "Data loaded";
}

getData().then(msg => console.log(msg));

Using await

await pauses the async function until the promise resolves. It makes asynchronous code read like synchronous code.

async function fetchUser(id) {
  const response = await fetch("https://api.example.com/users/" + id);
  const user = await response.json();
  console.log(user.name);
}

fetchUser(1);

Error Handling

Wrap await calls in try...catch to handle promise rejections gracefully.

async function loadData() {
  try {
    const result = await fetch("https://api.example.com/bad-url");
    console.log(await result.json());
  } catch (error) {
    console.error("Failed to load:", error.message);
  }
}

loadData();

๐Ÿงช Quick Quiz

What keyword do you use before a function to make it asynchronous?