正常使用new Function(script)构建的函数,里面无法使用await,因为new Function生成的函数不是async 函数。
故封装AsyncFunction来进行异步Function的使用:
方法一:(构造器, 只适用于原生js 、react、vue3、node端,vue2函数进行了处理不可用此方式)
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
使用:
let fn = new AsyncFunction(...args, script).bind(this);
await fn();
方式二(return 一个普通函数,使用起来与方式一一样):
function AsyncFunction(...params) {
let script = params.length ? params[params.length - 1] : "";
let args = params.length ? params.slice(0, params.length - 1) : [];
let func = new Function(`return async function(${args}){${script}}`).bind(this)();
return func;
}
使用:
let fn = new AsyncFunction(...args, script).bind(this);
await fn();