Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Asynchronous (async) code runs in the background without blocking the rest of your program. Like ordering coffee - you don't wait at the counter, you go sit down and they call you when it's ready!
console.log('Start');
// This blocks for 3 seconds
for(let i=0; i<3000000000; i++){}
console.log('End');
// Output:
// Start
// ...waits 3 seconds...
// EndEverything waits ❌
console.log('Start');
setTimeout(() => {
console.log('Timeout done');
}, 3000);
console.log('End');
// Output:
// Start
// End (immediately!)
// ...waits 3 seconds...
// Timeout doneDoesn't block! ✓
See the difference
Fetching data from servers takes time - don't freeze the UI!
Delays, intervals, animations - run code after a wait
Reading/writing files without blocking
Clicks, form submissions - respond when they happen
Where async is essential
Pass a function to be called when done
setTimeout(callback, 1000)Problem: Callback hell!
Return a promise object, chain with .then()
promise.then().catch()Much better!
Write async code like synchronous code
await promiseCleanest! ⭐
Fetching user data
JavaScript is single-threaded but can handle async tasks through the event loop:
Understanding execution order