Master JavaScript Promises: From Basics to Advanced API
This article explains what JavaScript Promises are, their immutable states, advantages and drawbacks, details the constructor, instance and static methods, provides code examples, and walks through the source implementations of resolve, reject, all, and race.
Promise Introduction
First, let’s understand what a Promise is.
Promise is an abstract asynchronous handling object and component for various operations.
Promise objects have two characteristics:
(1) The object's state is not affected by external factors. Promise represents an async operation with three states: Pending (in progress), Resolved/Fulfilled (completed), Rejected (failed).
Only the result of the async operation determines the state; no other operation can change it.
(2) Once the state changes, it never changes again; the result can be obtained at any time. The Promise object's state can change only two ways: from Pending to Resolved or from Pending to Rejected .
When these occur, the state is frozen. Even after the change, adding callbacks to the Promise will immediately receive the result.
The Promise object can express async operations in a synchronous flow, avoiding nested callbacks and providing a unified interface.
Drawbacks of Promise:
(1) It executes immediately upon creation and cannot be cancelled.
(2) If no callbacks are set, errors thrown inside the Promise are not propagated outward.
(3) While in Pending state, progress cannot be known.
Promise API
Constructor
Promiseis similar to XMLHttpRequest; using the Promise constructor creates a new promise object as an interface. Use new to instantiate.
Instance Method
Use promise.then() to set callbacks for when resolve (success) or reject (failure) is called.
onFulfilled, onRejected are optional parameters.
For handling only rejections, use promise.then(undefined, onRejected) or promise.catch(onRejected).
Static Method
Promise includes static methods: Promise.resolve(), Promise.reject(), Promise.all(), Promise.race().
First, look at the Promise workflow:
Example code:
asyncFunc()returns a promise that resolves after a 10 ms setTimeout, triggering the then callback which outputs “Hello Promise!”. In this case, the catch callback is not executed because the promise resolves.
Writing Promise Code
Creating a promise follows these steps:
(1) new Promise(fn) returns a promise object.
(2) Inside fn , specify the async operation: call resolve(value) on success, reject(Error) on failure.
Next, wrap an XHR request in a Promise named getUrl. The getURL function resolves when XHR returns status 200, otherwise rejects.
Promise Source Code
Promise.resolve
Static method Promise.resolve has three forms: Promise.resolve(value), Promise.resolve(promise), Promise.resolve(thenable). Each creates a new Promise so that then can be chained.
The implementation creates a new Promise instance, calls resolve, and returns it.
Example:
Promise.reject
Promise.rejectworks like Promise.resolve but rejects.
Promise.all
Promise.allcombines multiple promises into a new one. The implementation uses a counter: each resolved promise increments; when the counter equals the number of promises, the combined promise resolves.
The source code decrements a counter; when it reaches zero, the combined promise resolves with an array of results.
Promise.race
Promise.racealso combines multiple promises, but resolves or rejects as soon as any promise settles.
Conclusion
Reviewing Promises from start to source shows they are not as difficult as imagined.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaoDou Frontend Team
Open-source, innovative, collaborative, win‑win – sharing frontend tech and shaping its future.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
