咱们晓得 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://davidwalsh.name/async...
  • 原文中的method - https://davidwalsh.name/new-f...

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