ウェブサイト検索

クラス - TypeScript クラス: 複数のプロミスを必要とする変数をどのように初期化するか?


私の目的は、コンストラクタの中で 'page' 変数を初期化することです。問題は、コンストラクタ内で非同期/await のプロミスを実行できないことです。ですので、私の考えは「クラス内にメソッドを作り、コンストラクタ内で呼び出せばいい」と思ったのですが、もちろん間違っていました。TypeScriptはまだ、pageが確実に初期化されていないと私に警告します。実際のところ、非同期/awaitなしでブラウザ変数に対して 'newPage()' メソッドを呼び出すこともできません。この問題をどのように回避できますか?お時間をいただき、ありがとうございます。

class Puppet {
  private page: puppeteer.Page;
  
  contructor() {
    this.initialize();
  }

  async initialize(){
    const browser = await puppeteer.launch({headless:true});
    this.page = await browser.newPage();
    await this.page.goto(this.url);
  }
}

回答 #1

呼び出しメソッドから、まずオブジェクトを作成し、それから initialize() 関数を呼び出します:

class Puppet {
  private page!: puppeteer.Page;

  async initialize(){
    const browser = await puppeteer.launch({headless:true});
    this.page = await browser.newPage();
    await this.page.goto(this.url);
  }
}

// ... in some async function
const puppet = new Puppet();
await puppet.initialize();

これを少し便利にしたい場合は、非同期のファクトリー関数を追加してください:

class Puppet {
  private page!: puppeteer.Page;

  async #initialize(){
    const browser = await puppeteer.launch({headless:true});
    this.page = await browser.newPage();
    await this.page.goto(this.url);
  }

  static async create() {
      const puppet = new Puppet();
      await puppet.#initialize();
      return puppet;
  }
}

// ... in some async function
const puppet = await Puppet.create();

これにより、初期化をプライベート関数に隠すこともできます。