Menu
CoddyTech

When a Promise Fails

Part of the Node.js Basics section of Coddy's Node.js journey. Lesson 20 of 33.

A promise can also fail, for example when a file does not exist. That is called rejection. .catch supplies the code to run on failure. .finally runs after either success or failure, which is useful for a closing message.

readFile('weather.txt', 'utf8')
    .then((text) => console.log(text))
    .catch(() => console.log('No file'))
    .finally(() => console.log('Finished'));

When the read fails, its success callback is skipped. The example prints No file and then Finished. The failure message belongs in catch, so a successful read would not print it.

challenge icon

Challenge

Easy

Run practice.js first: the missing file causes an unhandled ENOENT error.

Keep the successful-read callback. Add .catch to print No notes yet on failure, then .finally to print Done for either outcome. With no arguments the lines are No notes yet and Done. Try note.txt: the lines are Buy milk and Done.

Try it yourself

import { readFile } from 'node:fs/promises';
readFile(process.argv[2] ?? 'missing.txt', 'utf8').then((text) => console.log(text));

All lessons in Node.js Basics

Practice on your own: Express playground