LearnFrenzy
Sign in Take a free test

Promises · Promises Coding Problems · Question 10

Load profile data in parallel with Promise.all in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links