LoginSignup
19
10

More than 5 years have passed since last update.

コンストラクタにasyncを指定するとシンタックスエラーになる

Last updated at Posted at 2018-01-13

状況

class MyClass {
  async constructor() {
    this.aaa = 'AAA'
    this.bbb = await hogehoge();
  }
}

const ccc = async () => {
  const ddd = await new MyClass();
};
Uncaught SyntaxError: Class constructor may not be an async method

対処法

class MyClass {
  constructor() {
    this.aaa = 'AAA'
  }
  async init() {
    this.bbb = await hogehoge();
  }
}

const createMyClass = async () => {
  const obj = new MyClass();
  await obj.init();
  return obj;
};

const ccc = async () => {
  const ddd = await createMyClass();
};

非同期処理をコンストラクタから分離する。

19
10
0

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
19
10