Master ES6 Promises: From Basics to Advanced Chaining Techniques
This article introduces ES6 Promise, explains its constructor, resolve and reject mechanisms, demonstrates chaining with then, error handling with catch, and shows advanced utilities like Promise.all and Promise.race, all illustrated with clear code examples and visual diagrams for JavaScript developers.
Introduction
ES6 introduced Promise to make asynchronous callbacks more elegant and readable. Nested callbacks can make JavaScript code hard to maintain, so Promise encourages a chain‑style function writing.
To get a quick feel, you can inspect the constructor with console.dir(Promise).
Promiseis a constructor that provides static methods such as all, reject, resolve, and prototype methods like then and catch. Instances created with new Promise inherit then and catch.
The constructor receives a function with two parameters, resolve and reject. For example:
new Promise((resolve, reject) => {
setTimeout(() => {
console.log('执行完成');
resolve();
}, 2000);
});The passed function executes immediately, while the resolve or reject callbacks are invoked later.
Using then you can handle the resolved value:
promiseFun().then(data => {
console.log(data);
});This is essentially the same as a traditional callback, but it separates the asynchronous operation from its handling.
Without Promise, you could achieve similar results by manually passing callbacks, but chaining becomes cumbersome when multiple asynchronous steps are involved.
Chaining Usage
The real power of Promise lies in its state management, allowing you to chain calls:
promiseFun1()
.then(result1 => {
console.log(result1);
return promiseFun2();
})
.then(result2 => {
console.log(result2);
return promiseFun3();
})
.then(result3 => {
console.log(result3);
});Each then receives the value passed to resolve from the previous step, enabling a clear, linear flow.
Reject Usage
The reject function sets the promise state to rejected. It is useful for handling failure cases:
function getNumber() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const num = Math.floor(Math.random() * 10);
if (num <= 5) {
resolve(num);
} else {
reject('Number too large');
}
}, 2000);
});
}
getNumber().then(
value => console.log('Success:', value),
err => console.log('Failure:', err)
);Catch Usage
catchworks like the second argument of then but also captures exceptions thrown in the resolved callback:
promiseFun()
.then(() => {
console.log(somedata); // somedata is undefined
})
.catch(reason => {
console.log('Caught error:', reason);
});Promise.all Usage
Promise.allruns multiple promises in parallel and resolves when all have finished, returning an array of results:
Promise.all([promiseFun1(), promiseFun2(), promiseFun3()])
.then(results => {
console.log('All results:', results);
});This pattern is ideal for pre‑loading resources before initializing a page.
Promise.race Usage
Promise.raceresolves or rejects as soon as the first promise settles:
Promise.race([promiseFun1(), promiseFun2(), promiseFun3()])
.then(first => {
console.log('First completed:', first);
});Summary
These are the core features of ES6 Promise. While the standard includes then, catch, all, and race, many libraries add sugar methods such as done, finally, success, and fail.
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.
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.
