Skip to main content

Promise, promise chain, promise.all vs promise.race

Promise

Promise is an object that represent the eventual completion or failure of an asynchronous operation. They provide a cleaner and more manageable way to handle asynchronous code compared to traditional callback-based approaches.

Promise states

  • Pending: The initial state, neither fulfilled nor rejected.
  • Fulfilled: The operation completed successfully.
  • Rejected: The operation failed

Create a Promise

let promise = new Promise((resolve, reject) => {
// Asynchronous operation
let success = true; // Assume the operation succeeds

if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
});

// Example of Usage
promise
.then((result) => {
console.log(result); // "Operation successful!"
})
.catch((error) => {
console.error(error); // "Operation failed!"
})
.finally(() => {
console.log("Operation completed."); // This runs no matter what
});

Promise chaining

Promise chaining is a technique in JavaScript that allows you to execute a sequence of asynchronous operations in a readable and efficient manner.

It leverages the .then() method provided by Promises, which enables you to define a callback function to be executed when a Promise is fulfilled (successfully resolved).

This callback function can itself return a Promise, creating a chain of asynchronous operations.

function fetchData(url) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { message: 'Data retrieved from ' + url };
resolve(data);
}, 1000);
});
}

function processData(data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const processedData = data.message.toUpperCase();
resolve(processedData);
}, 500);
});
}

fetchData('https://example.com/api/data')
.then(data => processData(data))
.then(processedData => console.log(processedData))
.catch(error => console.error(error));

Promise.all and Promise.race

Promise.all

Promise.all() takes an array of promises and returns a single promise that resolves when all the promises in the array have resolved.

If any of the promises reject, the entire Promise.all() promise rejects with the reason of the first promise that rejected.

Promise.all() enables concurrent parallel execution of multiple promises, improving performance by avoiding sequential processing

Example

const promise1 = Promise.resolve(10);
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'hello')
});
const promise3 = 20;

Promise.all([promise1, promise2, promise3]).then((values) => {
console.log(values); // [10, "hello", 20]
}).catch((error) => {
console.error(error);
});

Promise.race

Promise.race() is used when you need the first promise to resolve, and you don't care about the rest

Acts like a race between the promises.

Example

const promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise 1 resolved"), 3000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("Promise 2 resolved"), 1000);
});

Promise.race([promise1, promise2])
.then((value) => console.log(value))
.catch((error) => console.error(error));

// Output: "Promise 2 resolved" (whichever finishes first)

Summary

  • Promise is an object that represent the eventual completion or failure of an asynchronous operation.
  • Promise chaining is a technique in JavaScript used to handle asynchronous operations
  • Promise.all() waits for all promises to complete while Promise.race() return the result of the first completed promise

References