JavaScript:JavaScript Async/Await, Promises, and Promise.all
JavaScript•Async Programming

JavaScript Async/Await, Promises, and Promise.all

Learn how the Node.js event loop handles non-blocking I/O, writing synchronous-looking async code with async/await.

Syntax

async function fetchVal() { const res = await promise; return res; }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
async functionDeclarationReturns a Promise implicitly.
awaitOperatorPauses async function execution until Promise settles.
Promise.all()Static MethodRuns multiple promises in parallel.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Asynchronous Programming with Promises and Async/Await
const simulateApiCall = (service, delayMs) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ service: service, status: "SUCCESS", timeMs: delayMs });
    }, delayMs);
  });
};

async function loadApplicationData() {
  console.log("--- Starting Parallel Requests ---");
  const startTime = Date.now();

  // Run calls in parallel using Promise.all
  const results = await Promise.all([
    simulateApiCall("User-Profile", 30),
    simulateApiCall("Notifications", 20),
    simulateApiCall("Metrics", 40)
  ]);

  results.forEach(res => {
    console.log("Loaded " + res.service + " in " + res.timeMs + "ms");
  });
  console.log("All services loaded concurrently!");
}

loadApplicationData();
Expected Output:
--- Starting Parallel Requests ---
Loaded User-Profile in 30ms
Loaded Notifications in 20ms
Loaded Metrics in 40ms
All services loaded concurrently!

How It Works: Step-by-Step

  • Lines 2-8: Creates Promise simulating non-blocking network I/O with setTimeout.
  • Lines 15-19: Promise.all launches all 3 requests simultaneously rather than sequentially.
  • Lines 21-23: Awaited results are unwrapped as an array of responses.

Key Concepts

  • async functions always return a Promise, even when returning a raw primitive.
  • await pauses only the async function execution, keeping the event loop unblocked.
  • Use Promise.all for independent parallel calls, and for...of with await for sequential steps.

Common Mistake: Awaiting calls inside loops sequentially instead of using Promise.all for independent tasks

Awaiting in a loop runs tasks one after another, multiplying latency.

❌ Incorrect
for (const id of ids) { await fetchItem(id); } // Sequential slowdown!
✅ Correct
await Promise.all(ids.map(id => fetchItem(id))); // Runs all concurrently

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler