10-Minute Asynchronous JS Programming Power Streak
Maintain a learning habit in just 10 minutes Prog with these easy methods.
01. The Event Loop
02:00Understand how JavaScript handles background tasks using the Callback Queue. It doesn’t stop the program; it schedules for later.
console.log("Start");
setTimeout(() => console.log("Timer Finished"), 1000);
console.log("End");
// Output: Start, End, Timer Finished
02. The Promise Lifecycle
IMPORTANTA Promise is always in one of three states. Understanding this helps debug “hanging” code.
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: Operation completed successfully.
- Rejected: Operation failed.
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) resolve("Data received!"); // Transitions to Fulfilled
else reject("Error occurred!"); // Transitions to Rejected
});
03. Async/Await & Errors
01:30Writing asynchronous code that reads like synchronous JS learning habit code, coupled with robust try/catch blocks for safety.
async function fetchData() {
try {
const res = await fetch('https://api.example.com/data');
if (!res.ok) throw new Error("Network issue");
return await res.json();
} catch (err) {
console.error("Caught:", err.message);
}
}
04. Parallel Concurrency
01:30Don’t await sequentially if tasks are independent. Use Promise.all to fire them all at once.
// Executes simultaneously
const [user, settings] = await Promise.all([
fetchUser(id),
fetchSettings(id)
]);
05. Graceful Handling
ADDITIONALUnlike Promise.all (which fails if one fails), Promise.allSettled waits for everything to finish, regardless of success or failure.
const results = await Promise.allSettled([fetch(p1), fetch(p2)]);
results.forEach(result => {
if (result.status === 'fulfilled') console.log("Value:", result.value);
if (result.status === 'rejected') console.log("Reason:", result.reason);
});
06. The Race Pattern
01:00Use Promise.race to implement timeouts. Useful when you need a result fast or a fallback if the server hangs.
const timeout = new Promise((_, rej) =>
setTimeout(() => rej("Too slow!"), 5000)
);
// Whichever finishes first wins
await Promise.race([fetchData(), timeout]);
07. Success Search (Promise.any)
CONCEPTUALImportant distinction: Promise.any waits for the first success. If one fails, it keeps waiting for others. Promise.race stops as soon as anything happens.
// Useful for mirror servers: get the fastest successful response
try {
const firstSuccessfulResult = await Promise.any([
fetchFromServerA(),
fetchFromServerB()
]);
} catch (err) {
console.log("All servers failed");
}
08. Clean Cleanup
ADVANCEDHow to stop a network request that is no longer needed (e.g., user navigated away). Use AbortController.
const controller = new AbortController();
fetch('/api/large-data', { signal: controller.signal });
// Later, to cancel:
controller.abort();
09. Async Iteration
EXPERTWhen dealing with streams or paginated data, use for await...of to loop through async values as they arrive.
async function* generateStream() {
yield "Data Chunk 1";
await new Promise(r => setTimeout(r, 1000));
yield "Data Chunk 2";
}
for await (const chunk of generateStream()) {
console.log(chunk); // Logs as they arrive
}
10. Microtask Priority
00:30Expert tip: Promises (Microtasks) always execute before Timers (Macrotasks). This determines the “True” order of operations.
setTimeout(() => console.log("Macrotask"), 0);
Promise.resolve().then(() => console.log("Microtask"));
// Result: "Microtask" prints first!