From 4f1cf93bd612c68ce2a21a9ece6a6715b5dbc308 Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Wed, 16 Feb 2022 12:22:06 +0900 Subject: Web/JavaScript/Reference/Operators 以下の残りの記事を移行 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reference/operators/async_function/index.md | 98 ++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 files/ja/web/javascript/reference/operators/async_function/index.md (limited to 'files/ja/web/javascript/reference/operators/async_function/index.md') diff --git a/files/ja/web/javascript/reference/operators/async_function/index.md b/files/ja/web/javascript/reference/operators/async_function/index.md new file mode 100644 index 0000000000..f50d024a21 --- /dev/null +++ b/files/ja/web/javascript/reference/operators/async_function/index.md @@ -0,0 +1,98 @@ +--- +title: 非同期関数式 +slug: Web/JavaScript/Reference/Operators/async_function +tags: +- Function +- JavaScript +- Language feature +- Operator +- Primary Expression +translation_of: Web/JavaScript/Reference/Operators/async_function +--- +
{{jsSidebar("Operators")}}
+ +

async function キーワードは、式の中で async 関数を定義するために使用できます。

+ +

非同期関数は、 async function 文を使用して定義することもできます。

+ +

構文

+ +
async function [name]([param1[, param2[, ..., paramN]]]) {
+   statements
+}
+ +

ES2015 では、アロー関数を使用することもできます。

+ +

引数

+ +
+
name
+
関数名です。関数が無名の場合は省略可能です。名前は関数の本体内のみのローカルです。
+
paramN
+
関数に渡される引数名です。
+
statements
+
関数本体を構成する文です。
+
+ +

解説

+ +

async function 式は {{jsxref('Statements/async_function', 'async function statement')}} と非常に似ており、構文もほとんど同じです。async function 式と async function 文の主な違いは、async function 式が無名関数を生成するために関数名を省略できる点です。async function 式は、定義後直ちに実行される IIFE (即時実行関数式) として使用することもできます。詳細は関数の章を見てください。

+ +

+ +

シンプルな例

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+};
+
+const add = async function(x) { // 変数に代入された非同期関数式
+  let a = await resolveAfter2Seconds(20);
+  let b = await resolveAfter2Seconds(30);
+  return x + a + b;
+};
+
+add(10).then(v => {
+  console.log(v);  // 4 秒後に 60 を表示
+});
+
+(async function(x) { // IIFE として使用される非同期関数式
+  let p_a = resolveAfter2Seconds(20);
+  let p_b = resolveAfter2Seconds(30);
+  return x + await p_a + await p_b;
+})(10).then(v => {
+  console.log(v);  // 2 秒後に 60 を表示
+});
+
+ +

仕様書

+ + + + + + + + + + + + +
仕様書
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}
+ +

ブラウザーの互換性

+ +

{{Compat("javascript.operators.async_function")}}

+ +

関連情報

+ + -- cgit v1.2.3-54-g00ecf