⏱️

How to Use Async/Await in JavaScript

JavaScriptIntermediate

Handle asynchronous operations cleanly.

Code Example

JavaScript
// Async/Await in JavaScript
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function fetchData() {
  console.log("Starting...");
  
  await delay(100);
  console.log("Step 1 complete");
  
  await delay(100);
  console.log("Step 2 complete");
  
  return "All done!";
}

// Using the async function
fetchData().then(result => {
  console.log(result);
});

// Parallel execution
async function parallel() {
  const [a, b, c] = await Promise.all([
    delay(100).then(() => "Result A"),
    delay(100).then(() => "Result B"),
    delay(100).then(() => "Result C"),
  ]);
  console.log(`\nParallel: ${a}, ${b}, ${c}`);
}

parallel();

Explanation

async/await makes asynchronous code look synchronous. Use Promise.all() for parallel execution.

Related Tutorials