Home > Back-end >  Why I can't use await in async function constructor?
Why I can't use await in async function constructor?

Time:10-05

Well, I'm needing to run asynchronous code through a string. For this I am using async function constructor.

 const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor; // This returns an async function class

const stringCode = "await console.log('hello')";

new AsyncFunction(stringCode)();

The problem:

despite being an asynchronous function, when I use any await in the stringCode, it returns:

[ERROR] 21:21:00 SyntaxError: await is only valid in async functions and the top level bodies of modules.

So why can't I execute await in the async function constructor?

CodePudding user response:

Remember that you can only use async/await logic where you can use promises. Now, for your case, you cannot use promises in a constructor since a constructor (recall your OOP) must return an object that is to be constructed, not a promise. So essentially, your first statement in your logic is an object, not an async function.

Edit for more clarity:

const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor; // This returns an async function class

From your own comment, //returns an async function CLASS, actually, it's an object not a class because you instantiated it. Now, object is not the same with an async function.

  • Related