AdvancedLesson 14 of 16
Asynchronous Programming – JavaScript
Event loop, promises, async/await and typical pitfalls.
JavaScript runs code in one thread. Slow tasks (network, timers, files) run in the background and report back later via the event loop. Order: first the synchronous code, then microtasks (promises), then macrotasks (timers).
console.log("1 synchronous");
setTimeout(() => console.log("4 Timeout"), 0);
Promise.resolve().then(() => console.log("3 Promise"));
console.log("2 synchronous");A promise stands for a value that arrives later. async functions always return a promise, and await pauses the function (not the thread) until the result is available. With Promise.all, tasks run in parallel:
const warte = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function lade(name, ms) {
await warte(ms);
return name + " loaded";
}
async function main() {
const ergebnisse = await Promise.all([lade("A", 100), lade("B", 200), lade("C", 100)]);
console.log(ergebnisse); // takes ~200 ms instead of 400 ms
}
main();You catch errors in async functions with try/catch. Promise.allSettled waits for all of them, even if some fail; Promise.race takes the fastest one:
async function main2() {
try {
await Promise.reject(new Error("broken"));
} catch (e) {
console.log("Caught:", e.message);
}
const status = await Promise.allSettled([lade("X", 10), Promise.reject(new Error("no"))]);
console.log(status.map(s => s.status)); // ['fulfilled', 'rejected']
const erster = await Promise.race([warte(50).then(() => "slow"), warte(10).then(() => "fast")]);
console.log(erster);
}
main2();You fetch data from the network with fetch. Check response.ok, because HTTP errors do not raise an exception:
async function ladeRepo(name) {
const antwort = await fetch("https://api.github.com/repos/" + name);
if (!antwort.ok) throw new Error("HTTP " + antwort.status);
return antwort.json();
}
ladeRepo("nodejs/node")
.then(repo => console.log(repo.full_name, repo.stargazers_count))
.catch(e => console.log("Error:", e.message));Warning
forEach does not wait for async callbacks! Use for...of with await (one after another) or Promise.all(list.map(async ...)) (in parallel). An await inside a loop makes the tasks sequential – often needlessly slow.