Does async/await will allow us to be used on constructors?

谁都会走 提交于 2019-11-27 15:53:22

问题


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

class MyClass {
    async constructor(){
        return new Promise()
    }
}

回答1:


Without trying to fortune-tell about future decisions, let's concentrate on practicality and what is already known.

ES7, like ES6 before it will try to be a backwards compatible expansion to the language. With that in mind, a backwards compatible constructor function is essentially a regular function (with some runtime restrictions) that's meant to be invoked with the new keyword. When that happens, the function's return value gets special treatment, specifically, non-object return values are ignored and the newly allocated object is returned while object return values are returned as is (and the newly allocated object is thrown away). With that, your code would result in a promise being returned and no "object construction" would take place. I don't see the practicality of this and I suppose if anybody takes the time to find what to do with such code it will be rejected.




回答2:


To expand upon what Patrick Roberts said, you cannot do what you are asking, but you can do something like this instead:

class MyClass {
  constructor() {
     //static initialization
  }

  async initialize() {
     await WhatEverYouWant();
  }

  static async create() {
     const o = new MyClass();
     await o.initialize();
     return o;
  }
}

Then in your code create your object like this:

const obj = await MyClass.create();



回答3:


In a nutshell:

  1. Constructor is a function that needs to provide a concrete object.
  2. Async returns a promise; exactly opposite of concreteness.
  3. async constructor is conceptually conflicting.



回答4:


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)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"><code></code></pre>


来源:https://stackoverflow.com/questions/36363278/does-async-await-will-allow-us-to-be-used-on-constructors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!