aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/operators/async_function/index.html
blob: 40ee1e2feac35fc123fcffcc8f8b9a8c5b258cc3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
---
title: async function expression
slug: Web/JavaScript/Reference/Operators/async_function
tags:
  - JavaScript
  - 函数
  - 基本表达式
  - 实验性内容
  - 操作符
translation_of: Web/JavaScript/Reference/Operators/async_function
original_slug: Web/JavaScript/Reference/Operators/async允许声明一个函数为一个包含异步操作的函数
---
<div>{{jsSidebar("Operators")}}</div>

<div> </div>

<p><strong><code>async function</code></strong> 关键字用来在表达式中定义异步函数。当然,你也可以用 {{jsxref('Statements/async_function', '异步函数语句')}} 来定义。</p>

<h2 id="语法">语法</h2>

<pre class="syntaxbox">async function [<em>name</em>]([<em>param1</em>[, <em>param2[</em>, ..., <em>paramN</em>]]]) { <em>statements </em>}</pre>

<h3 id="参数">参数</h3>

<dl>
 <dt><code>name</code></dt>
 <dd>此异步函数的名称,可省略。如果省略则这个函数将成为匿名函数。该名称仅可在本函数中使用。</dd>
 <dt><code>paramN</code></dt>
 <dd>传入函数的形参名称。</dd>
 <dt><code>statements</code></dt>
 <dd>组成函数体的语句。</dd>
</dl>

<h2 id="描述">描述</h2>

<p>异步函数表达式与 {{jsxref('Statements/async_function', '异步函数语句')}} 非常相似,语法也基本相同。它们之间的主要区别在于异步函数表达式可以省略函数名称来创建一个匿名函数。另外,异步函数表达式还可以用在 {{Glossary("IIFE")}} (立即执行函数表达式,Immediately Invoked Function Expression) 中,更多信息见 {{jsxref('Reference/Functions', '函数')}}</p>

<h2 id="示例">示例</h2>

<h3 id="一个简单例子">一个简单例子</h3>

<pre class="brush: js">function resolveAfter2Seconds(x) {
  return new Promise(resolve =&gt; {
    setTimeout(() =&gt; {
      resolve(x);
    }, 2000);
  });
};

// async function expression assigned to a variable
var add1 = async function(x) {
  var a = await resolveAfter2Seconds(20);
  var b = await resolveAfter2Seconds(30);
  return x + a + b;
}

add1(10).then(v =&gt; {
  console.log(v);  // 4 秒后打印 60
});

(async function(x) { // async function expression used as an IIFE
  var p_a = resolveAfter2Seconds(20);
  var p_b = resolveAfter2Seconds(30);
  return x + await p_a + await p_b;
})(10).then(v =&gt; {
  console.log(v);  // 2 秒后打印 60
});
</pre>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>ES2017 中的初始定义</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<div>{{Compat("javascript.operators.async_function_expression")}}</div>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li>{{jsxref("Statements/async_function", "异步函数语句")}}</li>
 <li>{{jsxref("AsyncFunction")}} 对象</li>
 <li>{{jsxref("Operators/await", "await 操作符")}}</li>
</ul>