Promise.all
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 25 of 33.
Independent reads can supply different parts of one result. Start both operations, wait for their results, then use each result for its own purpose.
const [forecast, location] = await Promise.all([
readFile('forecast.txt', 'utf8'),
readFile('location.txt', 'utf8'),
]);
console.log(location + ': ' + forecast);Result order follows the input array, even if the second read finishes first. Your notes tool instead reads notes and a display setting. The prepared readJson helper handles missing and damaged files. Format note numbers before reversing display lines, so changing the view never changes which note a number identifies.
Challenge
EasyThis step opens the course’s prepared notes command-line tool project, rather than your project files from Async and Await (including store.js). Your earlier work stays in its own lesson. Read the supplied files before editing store.js. This copy contains the notes commands, JSON reader and configuration file.
The notes tool now needs both notes.json and settings.json. Its supplied readJson(name, fallback) helper keeps the existing file-error handling.
- In
store.js, replace the empty placeholders with the results of reading both files together withPromise.all. A missing notes file uses[]; missing settings use{}. - In
notes.js, thelistbranch already makes numbered lines. Whenstore.settings.sortisnewest, reverse those lines before printing. Any other setting keeps the original order.
Try list: after Notes for you, expect 2. Call Ada, 1. Buy milk. Change the setting to oldest and try again: the same numbers appear in ascending order. Restore newest before checking.
Try it yourself
import { existsSync } from 'node:fs';
import { readFile, writeFile } from 'node:fs/promises';
const file = 'notes.json';
const readJson = async (name, fallback) => {
if (!existsSync(name)) {
return fallback;
}
try {
return JSON.parse(await readFile(name, 'utf8'));
} catch (err) {
console.error(`${name} is damaged: ${err.message}`);
process.exit(1);
}
};
// Replace these placeholders with the two readJson results.
const notes = [];
const settings = {};
const store = {
notes,
settings,
async save() {
await writeFile(file, JSON.stringify(this.notes, null, 2));
},
async add(text) {
this.notes.push(text);
await this.save();
return this.notes.length;
},
async remove(n) {
const [text] = this.notes.splice(n - 1, 1);
await this.save();
return text;
},
};
export default store;
All lessons in Node.js Basics
Practice on your own: Express playground