Load a user's profile, courses and certificates in parallel, then print a summary. Compare the total time with loading them one after another.
Solution
main.js
let inFlight = 0, maxInFlight = 0;
const api = (data, ms) => {
maxInFlight = Math.max(maxInFlight, ++inFlight); // count requests running at the same time
return new Promise((r) => setTimeout(() => { inFlight--; r(data); }, ms));
};
const getProfile = () => api({ name: "Asha" }, 30);
const getCourses = () => api(["JavaScript", "React"], 20);
const getCertificates = () => api(["JS Basics"], 10);
Promise.all([getProfile(), getCourses(), getCertificates()]).then(([profile, courses, certs]) => {
console.log(`${profile.name}: ${courses.length} courses, ${certs.length} certificate`);
console.log(`requests running at once: ${maxInFlight} (total time ≈ 30 ms, not 60 ms)`);
});
Output Verified by running it on Node.js
Asha: 2 courses, 1 certificate
requests running at once: 3 (total time ≈ 30 ms, not 60 ms)
All three requests are in flight together (the counter reaches 3), so the total time is that of the slowest (≈30 ms) instead of the sum (≈60 ms). Destructuring the array of results keeps the code readable.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!