AsyncFunction
AsyncFunction
?构造函数用来创建新的?异步函数
对象,JavaScript 中每个异步函数都是?AsyncFunction
?的对象。
注意,AsyncFunction
并不是一个全局对象,需要通过下面的方法来获取:
Object.getPrototypeOf(async function(){}).constructor
语法
new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)
参数
arg1, arg2, ... arg
_N
_Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x
", "theValue
", or "a,b
".functionBody
A string containing the JavaScript statements comprising the function definition.
描述
传递给?AsyncFunction
?构造函数的所有参数,都会成为新函数中的变量,变量的名称和定义顺序与各参数相同。?
调用?AsyncFunction
构造函数时可以省略?new
,其效果是一样的。
属性
AsyncFunction.lengthAsyncFunction
构造函数的 length 属性,值为 1。AsyncFunction.prototype
通过原型对象可以为所有异步函数对象定义额外的属性。
AsyncFunction
?原型对象
属性
AsyncFunction.constructor
默认值为AsyncFunction
.AsyncFunction.prototype[@@toStringTag]
Returns "AsyncFunction".
AsyncFunction
?实例
AsyncFunction
实例继承了AsyncFunction.prototype
的方法和属性。和所有构造函数一样,修改?AsyncFunction
?构造函数的原型对象会同时对所有?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); // prints 30 after 4 seconds
});
规范
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262)The definition of 'AsyncFunction object' in that specification. | Draft | 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 |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com