LearnFrenzy
Sign in Take a free test

Async/Await · Async/Await Coding Problems · Question 10

A class with a static async factory in JavaScript Solution, output & explanation

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

Constructors cannot be async. Write a CourseReport class with a static async create(courseId) factory that loads data before returning a ready instance, and a summary() method.

Solution
main.js
const fakeDb = { js101: { title: "JavaScript Basics", students: [72, 88, 95, 61] } };
const loadCourse = (id) =>
  new Promise((res, rej) => setTimeout(() => (fakeDb[id] ? res(fakeDb[id]) : rej(new Error(`course ${id} not found`))), 5));

class CourseReport {
  #data;
  constructor(data) { this.#data = data; }                // plain, synchronous constructor
  static async create(courseId) {
    const data = await loadCourse(courseId);              // async work happens here
    return new CourseReport(data);
  }
  summary() {
    const { title, students } = this.#data;
    const avg = students.reduce((a, b) => a + b, 0) / students.length;
    return `${title}: ${students.length} students, average ${avg.toFixed(1)}`;
  }
}

(async () => {
  console.log((await CourseReport.create("js101")).summary());
  try {
    await CourseReport.create("py999");
  } catch (e) {
    console.log("Error:", e.message);
  }
})();

Output Verified by running it on Node.js

JavaScript Basics: 4 students, average 79.0
Error: course py999 not found

The factory awaits the loading and only then calls the synchronous constructor, so callers always receive a fully initialised object (or a rejected promise).

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