File tree Expand file tree Collapse file tree 1 file changed +26
-2
lines changed Expand file tree Collapse file tree 1 file changed +26
-2
lines changed Original file line number Diff line number Diff line change @@ -210,7 +210,7 @@ getTitle('https://tc39.github.io/ecma262/').then(console.log)
210210
211211### await 命令
212212
213- 正常情况下,` await ` 命令后面是一个 Promise 对象。如果不是,就返回对应的值 。
213+ 正常情况下,` await ` 命令后面是一个 Promise 对象,返回该对象的结果 。如果不是 Promise 对象,就直接返回对应的值 。
214214
215215``` javascript
216216async function f () {
@@ -225,6 +225,30 @@ f().then(v => console.log(v))
225225
226226上面代码中,` await ` 命令的参数是数值` 123 ` ,这时等同于` return 123 ` 。
227227
228+ 另一种情况是,` await ` 命令后面是一个` thenable ` 对象(即定义` then ` 方法的对象),那么` await ` 会将其等同于 Promise 对象。
229+
230+ ``` javascript
231+ class Sleep {
232+ constructor (timeout ) {
233+ this .timeout = timeout;
234+ }
235+ then (resolve , reject ) {
236+ const startTime = Date .now ();
237+ setTimeout (
238+ () => resolve (Date .now () - startTime),
239+ this .timeout
240+ );
241+ }
242+ }
243+
244+ (async () => {
245+ const actualTime = await new Sleep (1000 );
246+ console .log (actualTime);
247+ })();
248+ ```
249+
250+ 上面代码中,` await ` 命令后面是一个` Sleep ` 对象的实例。这个实例不是 Promise 对象,但是因为定义了` then ` 方法,` await ` 会将其视为` Promise ` 处理。
251+
228252` await ` 命令后面的 Promise 对象如果变为` reject ` 状态,则` reject ` 的参数会被` catch ` 方法的回调函数接收到。
229253
230254``` javascript
240264
241265注意,上面代码中,` await ` 语句前面没有` return ` ,但是` reject ` 方法的参数依然传入了` catch ` 方法的回调函数。这里如果在` await ` 前面加上` return ` ,效果是一样的。
242266
243- 只要一个 ` await ` 语句后面的 Promise 变为 ` reject ` ,那么整个` async ` 函数都会中断执行。
267+ 任何一个 ` await ` 语句后面的 Promise 对象变为 ` reject ` 状态 ,那么整个` async ` 函数都会中断执行。
244268
245269``` javascript
246270async function f () {
You can’t perform that action at this time.
0 commit comments