It is very unusual for me that if I wrote my class in TypeScript and call it something like this:

var result = new MyClass.search(...) 

That search() method will be called before the constructor finishes, if the constructor has to use asynchronous functions (node.js I / O). That is, the constructor has not yet completed the initialization of the object, and someone already calls the object's methods. Is it possible to do something similar (analogue spend with WinAPI):

 search(...) { waitForSingleObject(event) ... } 

And while the designer does his work and does not cause:

 setEvent(event) 

then the search() method will slow down? At the same time, of course, waitForSingleObject() should be a smart function and make it clear to the thread that while you can do other things and not slow down, say, the entire node.js platform?

PS I understand that the problem is not in TypeScript. In JS, the constructor function can also create methods for this and return control before it receives initialization data over the network, from the database, from the disk subsystem, etc.

  • 2
    It's simple: asynchronous functions should not be called in the constructor. The constructor does not start the operation of the object, it only makes sure that all invariants are in place (that is, the class is ready for work and the required fields are filled). - etki
  • Of course, performing asynchronous functions in a constructor is a bad idea, but if you really want to waitForSingleObject you can use async/await . - Vladimir Gamalyan
  • And what is an asynchronous constructor? - VladD
  • can then use EventEmitter better - pnp2000

1 answer 1

You misunderstand operator priority.

You think that result = new MyClass.search(...) will execute like this:

 var tmpObj = new MyClass; result = tmpObj.search(...); 

but JS actually understands this code like this:

 var tmpConstructor = MyClass.search(...); result = new tmpConstructor; 

In order for the code to work as in the first case, you need to place the parentheses. For example:

 result = (new MyClass).search(...);