AsyncFunction() 构造函数

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017.

AsyncFunction() 构造函数创建 AsyncFunction 对象。

¥The AsyncFunction() constructor creates AsyncFunction objects.

请注意,AsyncFunction 不是全局对象。可以通过以下代码获取:

¥Note that AsyncFunction is not a global object. It can be obtained with the following code:

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

AsyncFunction() 构造函数不适合直接使用,Function() 描述中提到的所有注意事项均适用于 AsyncFunction()

¥The AsyncFunction() constructor is not intended to be used directly, and all caveats mentioned in the Function() description apply to AsyncFunction().

语法

¥Syntax

js
new AsyncFunction(functionBody)
new AsyncFunction(arg1, functionBody)
new AsyncFunction(arg1, arg2, functionBody)
new AsyncFunction(arg1, arg2, /* …, */ argN, functionBody)

AsyncFunction(functionBody)
AsyncFunction(arg1, functionBody)
AsyncFunction(arg1, arg2, functionBody)
AsyncFunction(arg1, arg2, /* …, */ argN, functionBody)

注意:可以使用或不使用 new 来调用 AsyncFunction()。两者都会创建一个新的 AsyncFunction 实例。

¥Note: AsyncFunction() can be called with or without new. Both create a new AsyncFunction instance.

参数

¥Parameters

参见 Function()

¥See Function().

示例

¥Examples

从 AsyncFunction() 构造函数创建异步函数

¥Creating an async function from an AsyncFunction() constructor

js
function resolveAfter2Seconds(x) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

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

const fn = new AsyncFunction(
  "a",
  "b",
  "return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);",
);

fn(10, 20).then((v) => {
  console.log(v); // prints 30 after 4 seconds
});

规范

Specification
ECMAScript Language Specification
# sec-async-function-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看