AsyncFunction 构造函数 创建一个新的 async function 对象。在JavaScript中,每个异步函数实际上都是一个 AsyncFunction 对象。
请注意,AsyncFunction不是一个全局对象。可以通过运行以下代码获得。
Object.getPrototypeOf(async function(){}).constructor
语法
new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)
参数
arg1, arg2, ... argN- 函数的参数名。每个必须是一个字符串,且符合 JavaScript 有效标示符或者用逗号隔开的一组字符串。例如 "x","theValue",或者 "a,b"。
functionBody- 一段包括函数声明的 javascript 函数语句的字符串
描述
async function 对象,在AsyncFunction构造函数 实例化的时候创建. 这要比用 async function expression声明和调用一个异步函数效率低, 因为这些函数剩下的代码会被解析。
所有参数在函数创建时被当做标示名,按照它们传递时的顺序传递。
注意: 通过 AsyncFunction 构造函数创建的 async function 在当前上下文不创建闭包;而是在全局作用域创建的。因此它们运行的时候只能访问它们自己的本地变量和全局变量,而不是 AsyncFunction 构造函数调用的作用域。这是 eval 与 async function 表达式不同的地方.
把 AsyncFunction 构造函数作为函数调用 (不使用 new 操作符) 和把它当做构造函数调用的效果是一样。
属性
AsyncFunction.lengthAsyncFunction构造函数的length属性的长度是1AsyncFunction.prototype- 允许所有的异步函数对象添加属性
AsyncFunction 原型对象
属性
AsyncFunction.constructor- 默认值为
AsyncFunction. AsyncFunction.prototype[@@toStringTag]- Returns "AsyncFunction".
AsyncFunction 实例
AsyncFunction 实例继承了 AsyncFunction.prototype 的方法和属性。和所有的构造函数一样,你可以通过更改构造函数的属性对象,使得所有实例化出的AsyncFunction 对象也产生变化。
实例
通过 AsyncFunction 构造器创建一个异步函数
function resolveAfter2Seconds(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x);
}, 2000);
});
}
var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;
var a = new AsyncFunction('a',
'b',
'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
a(10, 20).then(v => {
console.log(v); // 4 秒后打印出 30
});
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript Latest Draft (ECMA-262) AsyncFunction object |
Living Standard | Initial definition in ES2017. |
兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Edge | Opera | Safari (WebKit) |
|---|---|---|---|---|---|---|
| Basic support | 55 | 52.0 (52.0) | ? | ? | 42 | ? |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| Basic support | ? | ? | 52.0 (52.0) | ? | 42 | ? | 55 |