class User { async constructor(userId) { const user = await getUser(userId) this.id = user.id; this.name = user.name; this.email = user.email; } ... }
JavaScript doesn’t allow class constructors to be async. We have to do any async actions outside of a constructor. Static class methods can help with this.
class User { static async init(userId) { const user = await getUser(userId); return new User(user); } constructor(user) { this.id = user.id; this.name = user.name; this.email = user.email; } } const me = await User.init(1)