File tree Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Expand file tree Collapse file tree 2 files changed +36
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://crafty-builder-6996.ck.page/e169c61186 ) .
12
12
13
- _ 1159 TILs and counting..._
13
+ _ 1160 TILs and counting..._
14
14
15
15
---
16
16
@@ -413,6 +413,7 @@ _1159 TILs and counting..._
413
413
- [ Resolve And Pass Multiple Values From A Then] ( javascript/resolve-and-pass-multiple-values-from-a-then.md )
414
414
- [ Running ES6 Specs With Mocha] ( javascript/running-es6-specs-with-mocha.md )
415
415
- [ Scoping Variables With A Block Statement] ( javascript/scoping-variables-with-a-block-statement.md )
416
+ - [ Sleep For A Bit In Async Code] ( javascript/sleep-for-a-bit-in-async-code.md )
416
417
- [ Sorting Arrays Of Objects With Lodash] ( javascript/sorting-arrays-of-objects-with-lodash.md )
417
418
- [ Splat Arguments To A Function] ( javascript/splat-arguments-to-a-function.md )
418
419
- [ Spread The Rest With ES6] ( javascript/spread-the-rest-with-es6.md )
Original file line number Diff line number Diff line change
1
+ # Sleep For A Bit In Async Code
2
+
3
+ A ` sleep ` utility function can be useful in a variety of situations. From
4
+ testing and debugging to simulating a delay in development.
5
+
6
+ Here is what that function can look like in its simplest form:
7
+
8
+ ``` javascript
9
+ function sleep (time ) {
10
+ return new Promise ((resolve ) => {
11
+ setTimeout (resolve, time)
12
+ })
13
+ }
14
+ ```
15
+
16
+ This function returns a promise that will resolve after the given number of
17
+ milliseconds.
18
+
19
+ As an example of how to use it, here is how we can simulate a delay in a fake
20
+ fetch function.
21
+
22
+ ``` javascript
23
+ async function fakeUserFetch (userId ) {
24
+ # add half a second of " network" latency
25
+ await sleep (500 )
26
+
27
+ const fakeResponse = {
28
+ id: userId,
29
+ email: " fake-email@example.com"
30
+ }
31
+
32
+ return Promise .resolve (fakeResponse)
33
+ }
34
+ ```
You can’t perform that action at this time.
0 commit comments