Skip to content

Commit 8a5fc97

Browse files
committed
Add Sleep For A Bit In Async Code as a JavaScript til
1 parent 9d280db commit 8a5fc97

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1159 TILs and counting..._
13+
_1160 TILs and counting..._
1414

1515
---
1616

@@ -413,6 +413,7 @@ _1159 TILs and counting..._
413413
- [Resolve And Pass Multiple Values From A Then](javascript/resolve-and-pass-multiple-values-from-a-then.md)
414414
- [Running ES6 Specs With Mocha](javascript/running-es6-specs-with-mocha.md)
415415
- [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)
416417
- [Sorting Arrays Of Objects With Lodash](javascript/sorting-arrays-of-objects-with-lodash.md)
417418
- [Splat Arguments To A Function](javascript/splat-arguments-to-a-function.md)
418419
- [Spread The Rest With ES6](javascript/spread-the-rest-with-es6.md)
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
```

0 commit comments

Comments
 (0)