Async ו-Await
חלק מהיחידה יסודות Node.js במסלול ה-Node.js של Coddy. שיעור 16 מתוך 24.
שרשרת של קריאות .then נקראת אחרת מהדרך שבה חושבים על השלבים: לקרוא, ואז לנתח, ואז לשמור.
בתוך פונקציית async, await ממתין עד שההבטחה תתיישב ומחזיר לך את הערך שלה. הבטחה שנכשלה זורקת שגיאה שם, ולכן try ו־catch מטפלים בה. במודול, await עובד גם ברמה העליונה.
import { readFile } from 'node:fs/promises';
const loadConfig = async () => {
try {
return JSON.parse(await readFile('config.json', 'utf8'));
} catch {
return {};
}
};
const config = await loadConfig();
console.log(config.port ?? 3000);פונקציית async תמיד מחזירה הבטחה, ולכן גם מי שקורא לה צריך להמתין לה. אם שוכחים await, מקבלים את ההבטחה עצמה, Promise { <pending> }, במקום את הערך שלה.
אתגר
קלstore.jsקורא וכותב כעת באמצעותnode:fs/promises. הוסיפו את ה־awaitהחסרים כדי שכל פקודה תפעל כבעבר.notes.jsממתין ל־store.addול־store.remove, שהן כעתasync.
הריצו תחילה את node notes.js list כדי לקרוא את השגיאה, ואז את add ואת done 1 כשהכול עובד.
נסו בעצמכם
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const file = 'notes.json';
// readFile ו-writeFile מחזירות כעת הבטחות. יש להמתין לכל אחת מהן באמצעות await.
const load = async () => {
if (!existsSync(file)) {
return [];
}
try {
return JSON.parse(readFile(file, 'utf8'));
} catch (err) {
console.error(`notes.json is damaged: ${err.message}`);
process.exit(1);
}
};
const store = {
notes: load(),
async save() {
writeFile(file, JSON.stringify(this.notes, null, 2));
},
async add(text) {
this.notes.push(text);
this.save();
return this.notes.length;
},
async remove(n) {
const [text] = this.notes.splice(n - 1, 1);
this.save();
return text;
},
};
export default store;
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.