Search code examples
node.jsasynchronousasync-awaitprototype

Nodejs async function prototype chain error


why this code compiles

var Person =  function() {
console.log("CALLED PERSON")};

Person.prototype.saySomething = function() {
console.log("saySomething PERSON")};

var ape = new Person();
ape.saySomething();

and this code throws error Cannot set property 'saySomething' of undefined

var Person =  async function() {
console.log("CALLED PERSON")};

Person.prototype.saySomething = function() {
console.log("saySomething PERSON")};

var ape = new Person();
ape.saySomething();

Solution

  • When you use async function() {}, you are declaring an asynchronous function object. That's different than a regular function object. The asynchronous function object does not have a prototype.

    So, when you try to do this:

    var Person =  async function() {
      console.log("CALLED PERSON")
    };
    
    Person.prototype.saySomething = function() {
      console.log("saySomething PERSON")
    };
    

    Person.prototype is undefined because there is no prototype on an asynchronous function object. Thus attempting to assign something to Person.prototype.saySomething causes the error you see because Person.prototype is undefined.

    There is some logic to this because an asynchronous function can't be used as a constructor because an asynchronous function always returns a promise so it can't ever return a new object as in let obj = new f(). So, there's no purpose in having a .prototype property because it can't be used that way.

    If you really wanted to asynchronously create an object, you could always create an async factory function that returns a promise that resolves with an object.