We know that the JavaScript language allows functions to be generated through Funtion (). Can async functions be generated this way?

One of the things I like about JavaScript is that there are many ways to do the same thing eventually, and creating functions is one example. There are several modes for creating functions, one of which is probably the one you’ll see least:

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

What if you want to create async using the new Function method? You have to be smart, thanks to MDN, to find an answer:

// Create an asynchronous function with a new method
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;

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

Using object.getProtoTypeof (async function(){}).constructor is very refreshing because the native method AsyncFunction does not exist at all. Now you can use it to create asynchronous functions.

link

  • David Walsh.name /async-funct…
  • In the originalmethod – Davidwalsh. Name/new – functio…
  • Translation address – github.com/liuvigongzu…

First address of translationGithub.com/liuvigongzu…