What are promises?
- Node.js course
- Beginner
- Lesson 88/116
- 5 min
Learn the Promise concept and its states.
What is a Promise?
In JavaScript, a Promise is an object representing the eventual result of a long-running operation. A Promise is in one of three states: pending, fulfilled or rejected. Once it moves from pending to fulfilled or rejected, the state never changes again.
A Promise is created with new Promise((resolve, reject) => {...}), which takes an executor function. The executor calls resolve(value) on success or reject(error) on failure. This lets you wait for an asynchronous result without blocking the program; you chain code that runs when the result arrives.
The Promise constructor
To create a Promise you write new Promise(executor). The executor takes two parameters: resolve and reject. When the async work is done you call resolve(value) to deliver the result; on error you call reject(error).
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("ok"), 100);
});Here setTimeout calls resolve after 100 ms, so p moves to fulfilled. The executor runs synchronously; the Promise stays pending until resolve or reject is called.
Practice Your turn: create a Promise
Create a Promise with new Promise((resolve, reject) => {...}). Inside the executor, use setTimeout to log a message after 10 ms and then call resolve("ready").
Starter code
// Create a Promise
// Use setTimeout to log a message and call resolveSample solution
new Promise((resolve, reject) => {
setTimeout(() => {
console.log("working");
resolve("ready");
}, 10);
});Expected output
working
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens after a Promise moves from pending to fulfilled?
- It can return to pending
- It can move to rejected
- A new Promise is created
- It never changes again Correct answer
Explanation: Once a Promise is fulfilled, its state is locked.
2 Fill in the blank: deliver the result with resolve
const p = new Promise((resolve, reject) => {
setTimeout(() => ____("ok"), 100);
});
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve("ok"), 100);
});
Explanation: Calling resolve fulfils the Promise.
3 Match the Promise states
| Term | Meaning |
|---|---|
pending |
waiting |
fulfilled |
completed |
rejected |
failed |