Waiting for a Value
Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 22 of 33.
An await expression lets you write the next step after the read, instead of inside a then callback. It waits for this promise and gives you its result. Other work can still run while the read is waiting.
const text = await readFile('name.txt', 'utf8');
console.log(text.toUpperCase());Without await, text would hold the promise, which has no string methods. These files are modules, so await is allowed outside a function. Inside a function, mark the function async. An async function also returns a promise to its caller.
Challenge
EasyRun practice.js first. The error says text.toUpperCase is not a function: text holds a promise, not the file text.
Make text hold the completed read before the program uses it. Keep the asynchronous file function. Run again: the output is BUY MILK.
Run with the argument other.txt: the supplied second file must print CALL ADA. Keep the supplied filename expression.
Try it yourself
import { readFile } from 'node:fs/promises';
const text = readFile(process.argv[2] ?? 'note.txt', 'utf8');
console.log(text.toUpperCase());
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