You cannot use await in a constructor

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.

Last Updated: 2024-04-25

I had this code as part of my payments integration:

class StripeIntegration {
  stripe: Stripe

  constructor(
    stripePublicKey
  ) {
    this.stripe = await loadStripe(stripePublicKey);
  }
}

But it wouldn't compile.

Why? Basically because await returns a promise whereas a constructor is supposed to return an instance of the object. Doing both at once is literally impossible.

Here's the fix, which uses a custom constructor:

class StripeIntegration {
  stripe: Stripe

  // We need to use a custom constructor to handle the fact that Stripe is async
  // and regular JS constructors cannot have async code.
  public static async boot(
    stripePublicKey
  ) {
    const stripe = await loadStripe(stripePublicKey);
    return new StripeIntegration(
      stripe
    );
  }

  constructor(
    stripe: Stripe
  ) {
  }
}

Resources