File tree Expand file tree Collapse file tree 1 file changed +18
-2
lines changed Expand file tree Collapse file tree 1 file changed +18
-2
lines changed Original file line number Diff line number Diff line change @@ -242,13 +242,29 @@ class Sleep {
242
242
}
243
243
244
244
(async () => {
245
- const actualTime = await new Sleep (1000 );
246
- console .log (actualTime );
245
+ const sleepTime = await new Sleep (1000 );
246
+ console .log (sleepTime );
247
247
})();
248
+ // 1000
248
249
```
249
250
250
251
上面代码中,` await ` 命令后面是一个` Sleep ` 对象的实例。这个实例不是 Promise 对象,但是因为定义了` then ` 方法,` await ` 会将其视为` Promise ` 处理。
251
252
253
+ 这个例子还演示了如何实现休眠效果。JavaScript 一直没有休眠的语法,但是借助` await ` 命令就可以让程序停顿指定的时间。下面给出了一个简化的` sleep ` 实现。
254
+
255
+ ``` javascript
256
+ async function sleep (interval ) {
257
+ return new Promise (resolve => {
258
+ setTimeout (resolve, interval);
259
+ })
260
+ }
261
+
262
+ // 用法
263
+ sleep (1000 ).then (
264
+ () => console .log (' done' )
265
+ );
266
+ ```
267
+
252
268
` await ` 命令后面的 Promise 对象如果变为` reject ` 状态,则` reject ` 的参数会被` catch ` 方法的回调函数接收到。
253
269
254
270
``` javascript
You can’t perform that action at this time.
0 commit comments