41
27

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.

async/awaitをclass構文と合わせて使う

Last updated at Posted at 2016-06-14
class Human {
  constructor(name) {
    this.name = name;
  }
  async sayHello() {
    return await this.asyncReturnSomething(`Hello! I'm ${this.name}!`)
  }
  asyncReturnSomething(something) {
    return new Promise((resolve, reject)=> {
        setTimeout(()=> {
            resolve(something);
        }, 1000);
    });
  }
}

(async ()=> {
  const greeting = await new Human('John').sayHello();
  console.log(greeting);
  console.log('Done!');
})();

=> 1000ms後に
Hello! I'm John!
さらにその後に
Done!

awaitasyncで修飾された関数内でしか使えない模様です。
上の例からはclassのメソッド自体にasyncをつけることが可能だとわかる。
playground

41
27
1

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
41
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?