Beginner Fundamentals
Promises
A Promise represents a value that will be available later. It is a cleaner way to handle asynchronous code than nested callbacks.
Using a Promise
A Promise has three states: pending, fulfilled, or rejected. You read the result with then and handle errors with catch.
const fs = require("fs/promises");
fs.readFile("note.txt", "utf8")
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error("Error:", err.message);
});
Creating a Promise
You build one with the Promise constructor. Call resolve on success and reject on failure.
function wait(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve("done"), ms);
});
}
wait(1000).then((result) => console.log(result)); // 'done' after 1s
Chaining
Each then returns a new Promise, so you can chain steps:
wait(500)
.then(() => "step 1")
.then((value) => console.log(value)); // 'step 1'
Summary
Promises make async flow easier to read than callbacks. Use then for results, catch for errors, and chain steps in order.