22
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 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;
}

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

エピローグ

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

22
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
22
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?