Async JavaScript in Node.jsLesson 2.2
Promises in Node.js: then, catch, and chaining
Promise constructor, resolve, reject, .then chaining, .catch, .finally, Promise.all, Promise.allSettled, util.promisify
Promises Represent Future Values
A Promise is an object that represents an asynchronous operation that will complete (or fail) in the future. Instead of passing a callback into a function, the function returns a Promise you can chain handlers onto.
const fs = require('fs').promises;
fs.readFile('./data.txt', 'utf8')
.then(data => {
console.log(data);
return fs.writeFile('./copy.txt', data);
})
.then(() => console.log('Copy written'))
.catch(err => console.error('Error:', err.message))
.finally(() => console.log('Done'));Promisify Callback APIs
Use util.promisify to wrap any error-first callback function into a Promise-returning one:
const { promisify } = require('util');
const readFile = promisify(require('fs').readFile);
readFile('./data.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));Promise.all for Parallel Operations
Run multiple async operations concurrently and wait for all to complete:
const [a, b] = await Promise.all([
fs.readFile('a.txt', 'utf8'),
fs.readFile('b.txt', 'utf8')
]);Use Promise.allSettled when you want results even if some fail — it never rejects.
