Two Independent Reads
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 24 of 33.
Two reads can start together when neither needs the result of the other. Promise.all takes their promises and returns one promise for an array of results. Await that array once.
const [name, city] = await Promise.all([
readFile('name.txt', 'utf8'),
readFile('city.txt', 'utf8'),
]);The first result belongs to the first promise, even if the second read finishes sooner. The square brackets assign the two results to separate variables. If either read fails, the combined promise rejects. Use separate awaits when one operation needs the previous result.
The supplied practice reader refuses a read that is awaited before the other one has started. It makes waiting too early visible; it does not measure execution speed.
Challenge
EasyThis is a small practice project. Its setup is provided; edit only practice.js.
Read note.txt and owner.txt with Promise.all. Use the results to print Ada: Buy milk. Keep note first in the input array. Run executes node practice.js.
Use the imported reader. Start both reads before waiting; sequential awaits are deliberately refused by this practice reader.
Use the supplied noteFile and ownerFile values. Run with other-note.txt other-owner.txt: expect Bo: Walk.
Try it yourself
import { readFile } from './reader.js';
const [noteFile = 'note.txt', ownerFile = 'owner.txt'] = process.argv.slice(2);
const note = '';
const owner = '';
console.log(owner + ': ' + note);
All lessons in Node.js Basics
1Running JavaScript on Node
Hello, NodeReading the CommandCommand-Line ArgumentsCommands4Asynchronous Node
Using a Callback ResultCallbacksA Promise ResultWhen a Promise FailsPromisesWaiting for a ValueAsync and AwaitTwo Independent ReadsPromise.allThe Event LoopTimersPractice on your own: Express playground