Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.
Ключевое слово async function
исползуется для определения асинхронной функции внутри выражений.
Вы также можете определить асинхронные функции при помощи инструкции async function.
Синтаксис
async function [name]([param1[, param2[, ..., paramN]]]) { statements }
Согласно спецификации ES2015, вы также можете использовать стрелочные функции.
Параметры
name
- Имя функции. Этот параметр может быть опущен, в этом случае говорят об анонимной функции. The name is only local to the function body.
paramN
- Имя аргумента, передаваемого функции.
statements
- Инструкции, составляющие тело функции.
Описание
An async function
expression is very similar to, and has almost the same syntax as, an async function statement
. The main difference between an async function
expression and an async function
statement is the function name, which can be omitted in async function
expressions to create anonymous functions. An async function
expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.
Примеры
Простой пример
function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); }, 2000); }); }; (async function(x) { // async function expression used as an IIFE var a = resolveAfter2Seconds(20); var b = resolveAfter2Seconds(30); return x + await a + await b; })(10).then(v => { console.log(v); // prints 60 after 2 seconds. }); var add = async function(x) { // async function expression assigned to a variable var a = await resolveAfter2Seconds(20); var b = await resolveAfter2Seconds(30); return x + a + b; }; add(10).then(v => { console.log(v); // prints 60 after 4 seconds. });
Спецификации
Specification | Status | Comment |
---|---|---|
ECMAScript Latest Draft (ECMA-262) Определение 'async function' в этой спецификации. |
Черновик | Initial definition in ES2017. |
Поддержка браузерами
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!
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 |
Смотри также
async function
AsyncFunction
objectawait