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:
| Parameter | Type | Description |
|---|---|---|
| async function | Declaration | Returns a Promise implicitly. |
| await | Operator | Pauses async function execution until Promise settles. |
| Promise.all() | Static Method | Runs multiple promises in parallel. |
Ready-to-Run Code Example
Executable in CompilraRun 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
JavaScript Exception Handling: try, catch, finally & throw
Handle runtime exceptions gracefully without crashing using try, catch, finally, and custom Error objects.
JavaScript Functions: Arrow Functions, Parameters, and Rest
Master function declarations, expressions, arrow functions, and rest parameters (...args).
JavaScript Variables: let, const, and var Explained
Learn how to declare variables in modern JavaScript using let, const, and var with block scoping.
JavaScript Online Compiler
Open in Compilra IDE
Run and test JavaScript on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.