JavaScript Internals (521 Qs)•Part 2: Promises, Callbacks, Async & Strict Mode (54 - 103)
What are the main rules of promise
A promise must follow a specific set of rules:
- A promise is an object that supplies a standard-compliant
.then()method - A pending promise may transition into either fulfilled or rejected state
- A fulfilled or rejected promise is settled and it must not transition into any other state.
- Once a promise is settled, the value must not change.
Practical Code Example
javascript
// Key Promise Rules:
// 1. Immutable State: Once resolved or rejected, state cannot change.
// 2. Guaranteed Asynchronous execution (always runs on Microtask Queue).
// 3. Chainable: .then() always returns a new Promise.
const promise = new Promise((resolve, reject) => {
resolve('Value 1');
resolve('Value 2'); // Ignored! State is already fulfilled.
});
promise.then((val) => console.log(val)); // Logs: 'Value 1'