Labs ICT
โญ Pro Login

Async & Await

1 min read | JavaScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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?