异步函数构造器 AsyncFunction

AsyncFunction 并不是一个全局对象

所以并不能通过 new Array() 的方式创建异步函数实例

如果想直接使用 AsyncFunction 构造函数,需要多加一步中间操作:

const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;

 

关于 Object.getPrototypeOf ,其可以返回指定类型实例对象的原型(prototype)

// 1.
const array = [];
Object.getPrototypeOf(array) === Array.prototype; // true

// 2.
const proto = {};
const instance = Object.create(proto);
Object.getPrototypeOf(instance) === proto; // true

// 3.
Object.getPrototypeOf(async function() {}) === Object.getPrototypeOf(async function() {}).constructor.prototype; // true

 

使用异步函数构造器创建异步函数的示例代码:

function wait2s(x) {
  return new Promise(resolve => window.setTimeout(resolve, 2000, x));  
}

const AsyncFunc = Object.getPrototypeOf(async function() {}).constructor;

// 不推荐这种创建方式(存在安全风险)
const asyncFn = new AsyncFunc('x', 'y', 'return await wait2s(1) + await wait2s(2);');

console.log('==>');
asyncFn().then(console.log);

 

更多详细信息可以查看 MDN: 

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction

posted @ 2021-11-18 11:38  樊顺  阅读(392)  评论(0编辑  收藏  举报