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.

MaoDou Frontend Team
MaoDou Frontend Team
MaoDou Frontend Team
Master JavaScript Promises: From Basics to Advanced API

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

Promise

is 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.reject

works like Promise.resolve but rejects.

Promise.all

Promise.all

combines 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.race

also 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptAsynchronousAPIPromisecode
MaoDou Frontend Team
Written by

MaoDou Frontend Team

Open-source, innovative, collaborative, win‑win – sharing frontend tech and shaping its future.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.