2

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);
5
  • await is for asynchronous functions, and as far as I know constructors can't be asynchronous. Why exactly do you want to do this? Commented Sep 20, 2019 at 19:05
  • what is a point of doing that ? Commented Sep 20, 2019 at 19:06
  • @TylerRoper That answer is an anti-pattern, and its writer conceded as much in the first paragraph. Commented Jan 20 at 9:15
  • As for the question, it very well makes sense to write e.g. await new Promise((ok, ko) => setTimeout(ok, 1000)); – although one would probably want to move the Promise constructor call to a helper function. This is not covered by the “duplicates” at all, though. Commented Jan 20 at 11:12
  • @dumbass It's possible, but not advised, just like the answer rightly stated at the time. You're responding to a closed question from 6 years ago, by the way. Commented Jan 20 at 19:46

1 Answer 1

5

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);
})();

Sign up to request clarification or add additional context in comments.

5 Comments

This seems sketchy, even if it does work. new Test() should "be" a Test, not a Promise.
"should" be? this is javascript! anything can be anything
@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
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 OOP (not just javascript, check out asynchronous initializers using CompletionStage in Java) already has a design pattern for this - user the Builder pattern

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.