ΕργασίαWrite async function double(n) that returns a Promise resolving to n*2 (use await on Promise.resolve(n*2)). Call it once with 7, log the awaited result.
async / await: Υπόσχεση αλυσίδων που διαβάζουν από πάνω προς τα κάτω
100 XP7 min
Θεωρία
Two syntaxes, one thing
// .then chain
function load() {
return fetch("/api/user")
.then(r => r.json())
.then(user => user.name);
}
// async / await
async function load() {
const r = await fetch("/api/user");
const user = await r.json();
return user.name;
}Both functions return a Promise. Both wait for fetch and json. The async version reads like synchronous code, which is why it won the syntax war.
Two rules
awaitcan only appear inside anasyncfunction (or at the top level of a module — C4-09).asyncfunctions always return a Promise. Evenasync function x() { return 5; }returnsPromise<5>, not5.
try / catch for errors
async function load() {
try {
const r = await fetch("/api/user");
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return await r.json();
} catch (err) {
console.error("load failed:", err);
return null;
}
}try/catch around await catches both network errors (the fetch threw) and your manual throws (the bad-status throw). That's the whole error model.
Don't forget to await
async function bad() {
fetch("/api/log"); // fire and forget — error swallowed, ordering unclear
}
async function good() {
await fetch("/api/log"); // sequential, errors propagate
}Forgetting await is the #1 async bug. The function continues immediately without waiting; errors disappear into the void. Lint rules can flag this.
🔒
Εγγράψου για να αρχίσεις να προγραμματίζεις
Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.
Εγγραφή — δωρεάν δοκιμή →Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.