我喜欢 JavaScript 的一点是,完成同一任务有多种方式,其中一个例子就是创建函数。函数有几种模式;最后一种你可能看到使用的是 new Function 方法:
/* new Function(arg1, arg2 (...), body) */
const myFunction = new Function('users', 'salary', 'return users * salary');
如果你想使用这个 new Function 方法来创建一个异步函数呢?你需要有点聪明,多亏了 MDN,我们有一个解决方案:
// 允许通过 new Function 创建异步函数的垫片
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 并不存在。我不认为我曾经使用过 new Function 模式,但这并不意味着你不会使用!现在你可以让它们成为异步的了!