Async and Await
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 16 of 24.
A chain of .then calls reads differently from how you think about the steps: read, then parse, then save.
Inside an async function, await pauses until a promise settles and gives you its value. A failed promise throws there, so try and catch handle it. In a module, await also works at the top level.
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);An async function always returns a promise, so its caller awaits it too. Forget an await and you get the promise itself, Promise { <pending> }, instead of its value.
Challenge
Easystore.jsnow reads and writes withnode:fs/promises. Add the missingawaits so every command works as before.notes.jsawaitsstore.addandstore.remove, which areasyncnow.
Run node notes.js list first to read the error, then add and done 1 once it works.
Try it yourself
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const file = 'notes.json';
// readFile and writeFile now return promises. Wait for each with 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;
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeCommand-Line ArgumentsCommands