June 2025
Intermediate to advanced
837 pages
24h 50m
English
A promise represents the result of an asynchronous operation and a kind of return value for such an operation that allows you to better handle asynchronicity in your application. What was only possible with libraries for a long time has now found its way into the JavaScript engine. Listing 16.20 shows how you can use promises based on a small example.
import { readFile } from 'fs'; function promisedReadFile(filename) { return new Promise((resolve, reject) => { readFile(filename, 'utf-8', (err, data) => { if (err) { reject(err); } else { resolve(data); } }); });} promisedReadFile('input.txt') .then((data) => { console.log('Content of the file: ', data); }) .catch((error) => { console.error('An error occured: ', error ...
Read now
Unlock full access