如何通过new Function创建 async 函数 - 译

我们知道 JavaScript 语言允许通过 Funtion()生成函数, async 函数能通过这种方式生成吗?

我喜欢 JavaScript 的一点是,有很多方法最终可以完成相同的功能,创建函数就是一个例子。创建函数有好几种模式,其中一种可能是你看到最少的一种 new Function method

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

如果你想使用new Function 方法创建async 函数该怎么写呢?你要机智一点,多亏了 MDN,找到了一个答案:

// 通过新的方法创建异步函数
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;

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

使用 Object.getPrototypeOf(async function(){}).constructor 这个方法非常清新,因为原生方法根本 AsyncFunction 不存在。现在你可以使用它创建异步函数了。

链接

译文首发地址 https://github.com/liuvigongzuoshi/blog

你可能感兴趣的:(javascript,es6)