How to create async function with new function


We know that the JavaScript language allows you toFuntion()Generating function,asyncCan functions be generated in this way?

What I like about JavaScript is that there are many ways to accomplish the same function in the end, and creating a function is an example. There are several ways to create functions, one of which may be the least you seenew Function method

/* new Function(arg1, arg2 (...), body) */
const myFunction = new Function('users', 'salary', 'return users * salary');

If you want to usenew FunctionMethod creationasyncHow to write a function? You have to be smart, thanksMDNAnd found an answer:

//Creating asynchronous functions with new methods
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;

const fetchPage = new AsyncFunction("url", "return await fetch(url);");
fetchPage("/").then(response => { ... });

useObject.getPrototypeOf(async function(){}).constructorThis method is very fresh, because the native method is very simpleAsyncFunctionnon-existent. Now you can use it to create asynchronous functions.


First address of translation