AsyncFunction

AsyncFunction 构造函数 creates a new async function object. In JavaScript, every asynchronous function is actually an AsyncFunction 对象。

注意: AsyncFunction is not a global object. It can be obtained with the following code:

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.

描述

async function objects created with the AsyncFunction constructor are parsed when the function is created. This is less efficient than declaring an async function with an 异步函数表达式 and calling it within your code, because such functions are parsed with the rest of the code.

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

注意: async functions created with the AsyncFunction constructor do not create closures to their creation contexts; they are always created in the global scope.

When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the AsyncFunction constructor was called.

This is different from using eval with code for an async function expression.

援引 AsyncFunction 构造函数作为函数 (不使用 new 运算符) 有相同效果若把它作为构造函数进行援引。

范例

Creating an async function from an AsyncFunction() constructor

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}
let AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
let 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
});
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'AsyncFunction object' in that specification.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
AsyncFunction Chrome 55 Edge 15 Firefox 52 IE No Opera 42 Safari 10.1 WebView Android 55 Chrome Android 55 Firefox Android 52 Opera Android 42 Safari iOS 10.3 Samsung Internet Android 6.0 nodejs 7.6.0
7.6.0
7.0.0
Disabled
Disabled From version 7.0.0: this feature is behind the --harmony runtime flag.

图例

完整支持
完整支持
不支持
不支持
用户必须明确启用此特征。
用户必须明确启用此特征。

另请参阅

Metadata