Modern web development is fundamentally based on asynchronous programming, and JavaScript promises are essential for effectively handling asynchronous activities. This post will examine several promise methods and prototype functions that let you use promises in JavaScript productively.
Promise Methods
JavaScript offers a variety of promise techniques to manage several promises simultaneously or one at a time. Now let's examine each of these approaches:
1. Promise.all(iterable)
The Promise.all() static method takes an iterable of promises as input and returns a single promise. This returned promise fulfills when all of the input's promises fulfill (including when an empty iterable is passes), with an array of the fulfillment values.
It rejects when any of the input's promises rejects, with this first rejection reason (Message).
let p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P1"), 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P2"), 2000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P3"), 3000);
});
Promise.all([p1, p2, p3])
.then((values) => console.log(values))
.then((error) => console.log(error.message));
// (3) ['Resolve P1', 'Resolve P1', 'Resolve P1']
// 0: "Resolve P1"
// 1: "Resolve P2"
// 2: "Resolve P3"
// length: 3
// [[Prototype]]: Array(0)
- Promise.allSettled(iterable)
The Promise.allSettled()
static method is similar to Promise.all()
, but it does not short-circuit when any of the promises in the iterable reject. Instead, it waits for all promises to either fulfill or reject and returns an array of objects representing the state of each promise, including its value or reason for rejection.
let p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P1"), 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Reject P2")), 2000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P3"), 3000);
});
Promise.allSettled([p1, p2, p3])
.then((results) => console.log(results));
// [
// { status: 'fulfilled', value: 'Resolve P1' },
// { status: 'rejected', reason: Error: Reject P2 at <anonymous>:4:38 },
// { status: 'fulfilled', value: 'Resolve P3' }
// ]
- Promise.race(iterable)
The Promise.race() static method takes an iterable of promises as input and returns a single promise that fulfills or rejects as soon as one of the input promises fulfills or rejects.
let p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P1"), 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P2"), 2000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P3"), 3000);
});
Promise.race([p1, p2, p3])
.then((value) => console.log(value));
// "Resolve P1" (p1 fulfills first)
- Promise.any(iterable)
The Promise.any()
static method takes an iterable of promises as input and returns a single promise that fulfills as soon as one of the input promises fulfills. It rejects only if all the input promises reject.
let p1 = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error("Reject P1")), 1000);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P2"), 2000);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Resolve P3"), 3000);
});
Promise.any([p1, p2, p3])
.then((value) => console.log(value))
.catch((error) => console.log(error.message));
// "Resolve P2" (p2 fulfills first)
- Promise.resolve(value)
The Promise.resolve()
static method creates a new promise that is already fulfilled with the specified value.
let resolvedPromise = Promise.resolve("Resolved Value");
resolvedPromise
.then((value) => console.log(value));
// "Resolved Value"
- Promise.reject(error)
The Promise.reject()
static method creates a new promise that is already rejected with the specified error.
let rejectedPromise = Promise.reject(new Error("Rejected Error"));
rejectedPromise
.catch((error) => console.log(error.message));
// "Rejected Error"
Prototype Functions
Prototype functions, in addition to promise methods, provide you excellent control over the management of promises. Investigate these prototype features:
Promise.catch(onRejected)
: Thecatch()
method is used to add a rejection handler to a promise. It is equivalent to callingthen(undefined, onRejected)
.Promise.finally(onFinally)
: Thefinally()
method allows you to specify a callback function that will be executed regardless of whether the promise is fulfilled or rejected. This is helpful for cleanup operations.Promise.then(Resolve, Reject)
: Thethen()
method is used to add both fulfillment and rejection handlers to a promise. It takes two arguments: a function to handle fulfillment and a function to handle rejection.
You can effectively manage asynchronous actions in your code by learning these prototype functions and promise methods in JavaScript.
Happy Coding 🎉
Top comments (3)
Your article on JavaScript promises is fantastic! It's clear, concise, and perfect. Your real-world examples make it relatable, and explaining prototype functions is a great touch. Your tone strikes the right balance between professionalism and approachability. Short paragraphs, bullet points, and subheadings make it easy to read.
Keep up the great work, and Thank You! 🎉
nice, short and simple, thank you.
Clear and short, well written