Can async/await be used in constructors?

前端 未结 4 1688
时光取名叫无心
时光取名叫无心 2020-12-14 16:21

As the question stated. Will I be allowed to do this:

class MyClass {
    async constructor(){
        return new Promise()
    }
}
4条回答
  •  误落风尘
    2020-12-14 17:05

    You can get a promise from the return value, and await on that:

    class User {
      constructor() {
        this.promise = this._init()
      }
      
      async _init() {
        const response = await fetch('https://jsonplaceholder.typicode.com/users')
        const users = await response.json()
        this.user = users[Math.floor(Math.random() * users.length)]
      }
    }
    
    (async () {
      const user = new User()
      await user.promise
      return user
    })().then(u => {
      $('#result').text(JSON.stringify(u.user, null, 2))
    }).catch(err => {
      console.error(err)
    })
    
    

提交回复
热议问题