aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/javascript/reference/operators/await/index.html
blob: 463f0e8ea1336b7b1465acc12f41faf00e409e5e (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
100
101
102
103
104
105
106
---
title: await
slug: Web/JavaScript/Reference/Operators/await
tags:
  - JavaScript
  - Promise
  - await
  - 实验性
  - 操作符
translation_of: Web/JavaScript/Reference/Operators/await
---
<div>{{jsSidebar("Operators")}}</div>

<p><code>await</code>  操作符用于等待一个{{jsxref("Promise")}} 对象。它只能在异步函数 {{jsxref("Statements/async_function", "async function")}} 中使用。</p>

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

<pre class="syntaxbox">[返回值] = await 表达式;</pre>

<dl>
 <dt>表达式</dt>
 <dd>一个 {{jsxref("Promise")}} 对象或者任何要等待的值。</dd>
 <dt>返回值</dt>
 <dd>
 <p>返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。</p>
 </dd>
</dl>

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

<p>await 表达式会暂停当前 {{jsxref("Statements/async_function", "async function")}} 的执行,等待 Promise 处理完成。若 Promise 正常处理(fulfilled),其回调的resolve函数参数作为 await 表达式的值,继续执行 {{jsxref("Statements/async_function", "async function")}}</p>

<p>若 Promise 处理异常(rejected),await 表达式会把 Promise 的异常原因抛出。</p>

<p>另外,如果 await 操作符后的表达式的值不是一个 Promise,则返回该值本身。</p>

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

<p>如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果。</p>

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

async function f1() {
  var x = await resolveAfter2Seconds(10);
  console.log(x); // 10
}
f1();

</pre>

<p>如果该值不是一个 Promise,await 会把该值转换为已正常处理的Promise,然后等待其处理结果。</p>

<pre class="brush: js">async function f2() {
  var y = await 20;
  console.log(y); // 20
}
f2();
</pre>

<p>如果 Promise 处理异常,则异常值被抛出。</p>

<pre class="brush: js">async function f3() {
  try {
    var z = await Promise.reject(30);
  } catch (e) {
    console.log(e); // 30
  }
}
f3();</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('Async Function', '#async-function-definitions', 'async function')}}</td>
   <td>{{Spec2('Async Function')}}</td>
   <td>提案</td>
  </tr>
 </tbody>
</table>

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

{{Compat}}

<h2 id="查看更多">查看更多</h2>

<ul>
 <li>{{jsxref("Statements/async_function", "async 函数")}}</li>
 <li>{{jsxref("Operators/async_function", "async 函数表达式")}}</li>
 <li>{{jsxref("AsyncFunction")}} object</li>
</ul>