--- title: 非同期関数式 slug: Web/JavaScript/Reference/Operators/async_function tags: - Experimental - Function - JavaScript - Operator - Primary Expression translation_of: Web/JavaScript/Reference/Operators/async_function ---
async function キーワードは、式内で async function を定義するために使用できます。
async function [name]([param1[, param2[, ..., paramN]]]) {
statements
}
nameparamNstatementsasync function 式は {{jsxref('Statements/async_function', 'async function statement')}} と非常に似ており、構文もほとんど同じです。async function 式と async function ステートメントの主な違いは、async function 式は匿名関数を生成するために関数名を省略できる点です。async function 式は、定義後直ちに実行される IIFE(即時実行関数式)として使用することもできます。詳細は function の章を見てください。
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.
});
| 仕様 | ステータス | コメント |
|---|---|---|
| {{SpecName('Async Function', '#async-function-definitions', 'async function')}} | {{Spec2('Async Function')}} | 提案 |
| 機能 | Chrome | Firefox (Gecko) | Internet Explorer | Edge | Opera | Safari (WebKit) |
|---|---|---|---|---|---|---|
| 基本サポート | {{CompatChrome(55)}} | {{CompatGeckoDesktop("52.0")}} | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatOpera(42)}} | {{CompatUnknown}} |
| 機能 | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|
| 基本サポート | {{CompatUnknown}} | {{CompatUnknown}} | {{CompatGeckoMobile("52.0")}} | {{CompatUnknown}} | {{CompatOpera(42)}} | {{CompatUnknown}} | {{CompatChrome(55)}} |