Menu
CoddyTech

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 icon

Challenge

Easy

This 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

Practice on your own: Express playground