LoginSignup
21
11

More than 3 years have passed since last update.

【JavaScript】constructor内じゃawaitが使えねえ!だったらこうだ!【TypeScript】

Posted at

プロローグ

image.png
あっそうだ!constructorにasyncつけるの忘れてたぜ!

image.png
は?

状況

  • asyncconstructorにつけると怒られる
  • かといってプロパティにPromiseが入るのは嫌だ

解決策

class hoge{
    constructor(b){
        this.a = b;
    }
    public static init = async () => {
        return new hoge(await unko());
    }
    private a;
}

非同期静的メソッドを用意して非同期処理を済ませ、そこからコンストラクタを呼び出す。

エピローグ

そういえばあのライブラリ、コンストラクタを使わずに静的メソッドでインスタンスを生成していたな…
そういうことだったのか…!?

21
11
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
11