3

The keyword await makes JavaScript wait until that promise settles and returns its result.

I noticed its possible to await a function

var neonlight = await neon();

Is it possible to await a class?

Example

var neonlight = await new Neon(neon_gas);
Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
xaander1
  • 1,064
  • 2
  • 12
  • 40
  • `await` is for asynchronous functions, and as far as I know constructors can't be asynchronous. Why exactly do you want to do this? – John Montgomery Sep 20 '19 at 19:05
  • what is a point of doing that ? – Noob Sep 20 '19 at 19:06
  • 2
    I don't like that this was closed as a duplicate in favor of a bunch of dated (and wrong) answers stating **"this isn't possible"**, when clearly given Taki's answer below, it *is* possible. I am voting to reopen this question, in favor of marking *those* as duplicates of *this* question. – Tyler Roper Sep 20 '19 at 19:31

1 Answers1

6

Technically .. Yes, If the constructor returns a Promise and as long as the await is inside an async function, here's an example ( might not be the best, actually it's a bad practice to have a constructor function return a Promise , but it's just to get this to work ):

class Test {
  constructor() {
    return new Promise((res, rej) => {      
      this.getData().then(({userId, title}) => {
        this.userId = userId;
        this.title = title;
        
        res(this);
      });
    });
  }
  
  getData(){
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())      
  }
  
  greet(){    
    console.log('hello');
  }
}


(async() => {
  const x = await new Test();
  console.log(x.userId, ' : ', x.title);
})();
Taki
  • 17,320
  • 4
  • 26
  • 47
  • 1
    This seems sketchy, even if it does work. `new Test()` should "be" a `Test`, not a `Promise`. – crashmstr Sep 20 '19 at 19:10
  • 2
    "should" be? this is javascript! anything can be anything – Kevin B Sep 20 '19 at 19:11
  • 2
    @crashmstr you can have the promise resolve with `this` : `res(this)` to have `Test` instead of `hello` , i can't think of a real usecase for this but .. *Technically, it's possible* – Taki Sep 20 '19 at 19:19
  • 1
    **use case** Am writing some code that use knex _(knex uses promises to query the database)_ ... i want to re-use a class... i could re-use a function...a class seems more majestic and orderly. Great help @Taki. – xaander1 Sep 20 '19 at 20:17
  • @xaander1 OOP (not just javascript, check out asynchronous initializers using CompletionStage in Java) already has a design pattern for this - user the Builder pattern – slebetman Sep 21 '19 at 01:31