AsyncFunction()-Konstruktor
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.
Der AsyncFunction()-Konstruktor erstellt AsyncFunction-Objekte.
Beachten Sie, dass AsyncFunction kein globales Objekt ist. Es kann mit folgendem Code erhalten werden:
js
const AsyncFunction = async function () {}.constructor;
Der AsyncFunction()-Konstruktor ist nicht dafür vorgesehen, direkt verwendet zu werden, und alle Einschränkungen, die in der Beschreibung von Function() erwähnt werden, gelten auch für 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)
Hinweis:
AsyncFunction() kann mit oder ohne new aufgerufen werden. Beide Methoden erstellen eine neue Instanz von AsyncFunction.
Parameter
Siehe Function().
Beispiele
>Erstellen einer asynchronen Funktion aus einem AsyncFunction()-Konstruktor
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
});
Spezifikationen
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-async-function-constructor> |