动态创建异步功能 [英] Dynamically create async function
问题描述
我想知道是否可以动态创建这样的异步函数:
I am wondering if it is possible to dynamically create an async function like this:
new Function('await Promise.resolve()');
预计,上一个代码将抛出:
Expectedly, the previous code throw:
Uncaught SyntaxError: await is only valid in async function
推荐答案
Yes, you can use the (non-global) AsyncFunction constructor to dynamically create async functions in a similar way to how new Function(...)
works.
这是一个简单的例子:
const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
function createAsync(){
return new AsyncFunction('a', `return new Promise((resolve) => {
setTimeout(() => {resolve(a)}, 1000)
});`);
}
let asyncFn = createAsync();
asyncFn(1).then(/* chain the promise */);
// or inside some async function
async function myFunction(){
await asyncFn(1);
}
请记住,您可以在动态创建的异步函数中使用await
:)
And remember that you can use await
inside the dynamically created async function :)
注意:AsyncFunction
构造函数不是不是全局变量(例如Function
是),唯一引用它的方法是通过async function(){}
实例的原型,例如在MDN文档中提到.
NOTE: The AsyncFunction
contructor is not a global (like Function
is), the only way to get a reference to it is via the prototype of an async function(){}
instance, as mentioned in the MDN docs.
这篇关于动态创建异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!