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

Recommended Today

Practice of query operation of database table (Experiment 3)

Following the previous two experiments, this experiment is to master the use of select statements for various query operations: single table query, multi table connection and query, nested query, set query, to consolidate the database query operation.Now follow Xiaobian to practice together!Based on the data table (student, course, SC, teacher, TC) created and inserted in […]