How to create async function with new function

Time:2021-1-25

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;

//Use
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.

link

First address of translationhttps://github.com/liuvigongzuoshi/blog