Async JavaScript & Promises
Master asynchronous JavaScript with Promises, async/await, and the Fetch API for real-world data fetching.
0 of 10 concepts completed (0%)
What You'll Learn
Tutorial Contents
1.The Event Loop
JavaScript is single-threaded. The event loop manages concurrency through a queue system.
// Execution order: synchronous → microtasks → macrotaskssetTimeout(() => console.log("4"), 0); // macrotask queue
Promise.resolve() .then(() => console.log("3")); // microtask queue
console.log("2"); // synchronous
// Output: 1, 2, 3, 4 // Sync runs first, then ALL microtasks (Promises), then macrotasks (setTimeout) ```
2.Promises & Combinators
// Promise.all all must succeed, runs in PARALLEL
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts(),// Promise.allSettled waits for all, handles failures const results = await Promise.allSettled([ fetchUser(1), fetchUser(-1), // will reject ]); results.forEach(r => { if (r.status === "fulfilled") console.log(r.value); else console.error(r.reason); });
// Promise.race first to settle (fulfilled or rejected) const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout")), 5000) ); const data = await Promise.race([fetchData(), timeout]);
// Promise.any first to SUCCEED const fastest = await Promise.any([mirror1, mirror2, mirror3]); ```
3.Async/Await Best Practices
// Always handle errors
async function loadProfile(userId) {
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw new Error(`HTTP ${res.status}: ${res.statusText}`);
return res.json();// Parallel requests (much faster!) async function loadParallel() { const [user, stats] = await Promise.all([fetchUser(1), fetchStats()]); return { user, stats }; }
// Retry with exponential backoff async function fetchWithRetry(url, maxRetries = 3) { for (let attempt = 0; attempt <= maxRetries; attempt++) { try { return await fetch(url).then(r => r.json()); } catch (err) { if (attempt === maxRetries) throw err; await new Promise(r => setTimeout(r, Math.pow(2, attempt) * 1000)); } } }
// AbortController cancel stale requests
let controller;
async function search(query) {
if (controller) controller.abort();
controller = new AbortController();
const res = await fetch(/search?q=${query}, {
signal: controller.signal
});
return res.json();
}
```
Code Example
// Promise
const fetchUser = (id) =>
new Promise((resolve, reject) => {
setTimeout(() => resolve({ id, name: "Sufi" }), 1000);
});
// Async/Await
async function loadData() {
try {
const res = await fetch("https://api.example.com/data");
const data = await res.json();
return data;
} catch (error) {
console.error("Error:", error);
}
}
// Parallel requests
const [users, posts] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json()),
]);Pro Tips
- 1Always use try/catch with async/await. Unhandled promise rejections crash Node.js in newer versions and silently fail in browsers.
- 2Promise.all runs requests in parallel use it whenever requests are independent. Sequential awaits double or triple your response time unnecessarily.
- 3The fetch API doesn't throw on HTTP errors (4xx, 5xx). Always check response.ok explicitly.
- 4AbortController lets you cancel stale requests when new ones arrive essential for search-as-you-type patterns.
Topics Covered
Continue Learning
Explore the official documentation and deepen your knowledge with real-world practice.
Explore the Full Portfolio
This is the complete portfolio of Sufi Khan Sulaiman, a technology leader specialising in B2B commerce and digital automation. Start from the Home page for the overview, then move through two decades of career experience across FLIR Systems, Lorex Technology, and 1c Platform, and the full catalogue of project case studies spanning headless commerce migrations, AI recommendation engines, and multi-channel fulfilment systems.
The skills and certifications page maps the technical and leadership capabilities behind the work, while the articles and the knowledge base break down the thinking into actionable frameworks. For hands-on learning, the tutorials and applications sections cover practical builds from front-end fundamentals to full-stack web apps.
For consulting engagement, the expertise page outlines service offerings, the ecommerce hub covers platform architecture and automation strategy, and the ecommerce guide (PDF) is a downloadable 55-page field manual. When you are ready to talk, the contact page is the direct line.