#JavaScript
new AsyncFunction
the Async Version of new Function
I just learned about new AsyncFunction
which is the async version of new Function
. I had never heard of it before, but it is in the MDN docs.
What's the Problem?
Well, the problem is that new Function
is not async, so you cannot use await
inside of it. For example the following will wail:
> const fn = new Function('await Promise.resolve(1)');
> fn();
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
The problem is the await
keyword, which is only allowed inside an async functions (the jskata). Normally a function where await
is used inside needs to be created like this:
const fn = async () => {}
or async function fn() {}
. The function without the async
is a syntax error, as we also get it above.
The Solution
The solution is to use new AsyncFunction
instead of new Function
. Though creating the AsyncFunction
is not very intuitive, imho.
> const AsyncFunction = async function () {}.constructor;
> const fn = new AsyncFunction('await Promise.resolve(1)');
> fn();
Promise { 1 }
The above code is from the according MDN docs.