AsyncFunction() constructor
Baseline Widely available
The AsyncFunction() constructor creates AsyncFunction objects.
Note that AsyncFunction is not a global object. It can be obtained with the following code:
const AsyncFunction = async function () {}.constructor;
The AsyncFunction() constructor is not intended to be used directly, and all caveats mentioned in the Function() description apply to AsyncFunction().
Syntax
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)
Note: AsyncFunction() can be called with or without new. Both create a new AsyncFunction instance.
Creating an async function from an AsyncFunction() constructor
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);
});
Specifications
Browser compatibility
|
Desktop |
Mobile |
Server |
|
Chrome |
Edge |
Firefox |
Opera |
Safari |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
WebView Android |
Deno |
Node.js |
AsyncFunction |
55 |
15 |
52 |
42 |
10.1 |
55 |
52 |
42 |
10.3 |
6.0 |
55 |
1.0 |
7.6.0 |