Explain how Promise.all() works.

๐ Web Designer and learning full Stack Web development.
Search for a command to run...

๐ Web Designer and learning full Stack Web development.
No comments yet. Be the first to comment.
In this series, we'll together go on a journey to explore Frontend Interview Questions and what would be the ideal responses with diagrams and code examples.
Learn about how javascript object works, how we can create our own objects, take a sneak peek into console object and much more!

โ Scope ๐ฅ Scope defines the area, where functions, variables and other things are available or can be accessed. In layman's terms, scope means where to look for things, what things I can use and what I cannot! Let's take an example, here we are defi...

Learn about Array functions in JS with examples.

Beginners guide to Tailwind with a small project

Promise.all() is a JavaScript method that takes an array of promises as input and returns a single promise that resolves when all of the input promises have resolved, or rejects if any of the input promises are rejected. It is useful for aggregating the results of multiple promises.
It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully โ all of which we want to fulfill before the code execution continues.

// Promises Mock
const p1 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("p1");
}, 3000);
});
};
const p2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("p2");
// reject("p2");
}, 1000);
});
};
const p3 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("p3");
}, 2000);
});
};
Promise.all([p1(), p2(), p3()])
.then((values) => console.log(values))
.catch((err) => console.error(err));
//Output:
// In case all promises resolves โ
: [p1, p2, p3]
// In case p2 fails โ: p2
Promise.all() then starts an internal loop that iterates over the input promises. For each promise in the array, Promise.all() checks the status of the promise. If the promise has resolved, Promise.all() adds the result of the promise to an array. If the promise has rejected, Promise.all() rejects the new promise.
const promiseAll = (promises) => {
const results = [];
let count = 0;
return new Promise((resolve, reject) => {
promises.forEach((task, i) => {
task
.then((val) => {
count++;
results[i] = val;
})
.catch((err) => {
reject(err);
})
.finally(() => {
if (count >= promises.length) {
resolve(results);
}
});
});
});
};
Checkout more questions in the series: https://blog.prateekbudhiraja.in/series/frontend-interview