JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
Explain the three states of promise
Promises have three states:
- Pending: This is an initial state of the Promise before an operation begins
- Fulfilled: This state indicates that the specified operation was completed.
- Rejected: This state indicates that the operation did not complete. In this case an error value will be thrown.
Practical Code Example
javascript
// 1. Pending: Initial state, neither fulfilled nor rejected
const p = new Promise((resolve, reject) => {
// Currently pending...
setTimeout(() => resolve('Data loaded'), 1000); // Transitions to Fulfilled
// or reject(new Error('Failed')) // Transitions to Rejected
});
console.log(p); // Promise { <pending> }
p.then(result => console.log('Fulfilled:', result));