-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
290 lines (254 loc) · 14.7 KB
/
index.html
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"><title>JavaScript Async/Await 101 - hakaselogs</title><link rel="icon" type="image/png" href=/images/favicon.png /><meta name="viewport" content="width=device-width, initial-scale=1">
<meta itemprop="name" content="JavaScript Async/Await 101">
<meta itemprop="description" content="A simple guide to getting started with Async and Await in JavaScript">
<meta itemprop="dateModified" content="2017-08-12T00:00:00+00:00" />
<meta itemprop="wordCount" content="845">
<meta itemprop="keywords" content="javascript,async/await," />
<meta property="og:title" content="JavaScript Async/Await 101" />
<meta property="og:description" content="A simple guide to getting started with Async and Await in JavaScript" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://hakaselogs.me/2017-08-12/javascript-async/await-101/" />
<meta property="article:published_time" content="2017-08-12T00:00:00+00:00" />
<meta property="article:modified_time" content="2017-08-12T00:00:00+00:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="JavaScript Async/Await 101"/>
<meta name="twitter:description" content="A simple guide to getting started with Async and Await in JavaScript"/>
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" media="screen" href="https://hakaselogs.me/css/normalize.css" />
<link rel="stylesheet" type="text/css" media="screen" href="https://hakaselogs.me/css/main.css" />
<link id="dark-scheme" rel="stylesheet" type="text/css" href="https://hakaselogs.me/css/dark.css" />
<script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
<script src="https://hakaselogs.me/js/main.js"></script>
</head>
<body>
<div class="container wrapper">
<div class="header">
<div class="avatar">
<a href="https://hakaselogs.me/">
<img src="https://storage.googleapis.com/gopherizeme.appspot.com/gophers/0f1736136b4fcbea61798f9d4d04a6b01f4a05ad.png" alt="hakaselogs" />
</a>
</div>
<h1 class="site-title"><a href="https://hakaselogs.me/">hakaselogs</a></h1>
<div class="site-description"><p>Notes mostly about software engineering and what I’m working on.</p><nav class="nav social">
<ul class="flat"><li><a href="https://twitter.com/codehakase" title="Twitter"><i data-feather="twitter"></i></a></li><li><a href="https://github.com/codehakase" title="Github"><i data-feather="github"></i></a></li></ul>
</nav>
</div>
<nav class="nav">
<ul class="flat">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/posts">Archive</a>
</li>
<li>
<a href="/projects">Projects</a>
</li>
<li>
<a href="/tags">Tags</a>
</li>
</ul>
</nav>
</div>
<div class="post">
<div class="post-header">
<div class="meta">
<div class="date">
<span class="day">12</span>
<span class="rest">Aug 2017</span>
</div>
</div>
<div class="matter">
<h1 class="title">JavaScript Async/Await 101</h1>
</div>
</div>
<div class="markdown">
<p><img src="/images/aysnc-await.png" alt="async/await" title="Async/await"></p>
<p>Async and Await has been a blessing to most JavaScript Developers. Even while it was on the <a href="https://github.com/tc39/ecma262/tree/82bebe057c9fca355cfbfeb36be8e42f18c61e94">Stage 4 proposal</a> for ES6, the feature has been warmtly welcomed.</p>
<p>Node.js now Supports async/await since its version 7.6.</p>
<h2 id="what-is-asyncawait">What is async/await?</h2>
<p>If this is your first time seeing/hearing of this term, here’s it in plain English:</p>
<ul>
<li>Its the newest way/pattern of writing asychronous code in JavaScript, asides Promises and callbacks.</li>
<li>Async/await compared to Promises, are non-blocking</li>
<li>Async/await makes aysnchronous code appear and behave like synchronous code.</li>
<li>Aysnc/await cannot be used with plain callbacks</li>
</ul>
<h4 id="asyncawait-vs-promises-syntax">Async/Await Vs Promises (Syntax)</h4>
<p>Lets write a function that returns a Promise, which resolves with some data object. When its called, it logs, and return something:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">const</span> bookTaxi = () => {
getAvailableDrivers()
.then (drivers => {
console.log(drivers)
<span style="color:#00f">return</span> <span style="color:#a31515">"done"</span>
})
}
bookTaxi()
</code></pre></div><p>Implementing same with async/await:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">const</span> bookTaxi = async () => {
console.log(await getAvailableDrivers() )
<span style="color:#00f">return</span> <span style="color:#a31515">"done"</span>
}
bookTaxi()
</code></pre></div><ul>
<li>
<p>The second snippet, has the <code>async</code> keyword before it. The <code>await</code> keyword can only be used inside functions defined with the <code>async</code> keyword. The Async functions returns a promise, and the resolved value of the promise wil be whatever is returned from the function.</p>
</li>
<li>
<p>The <code>await getAvailableDrivers()</code> inside the <code>console.log</code> literal means the call will wait until the promise <code>getAvailableDrivers()</code> resolves and prints its value.</p>
</li>
</ul>
<blockquote>
<p>The <code>async</code> function declaration defines an asynchronous function, which returns an AsycFunction object.</p>
</blockquote>
<blockquote>
<p>The <code>await</code> operator is used to wait fro a Promise. It can only be used inside an <code>async</code> function - MDN</p>
</blockquote>
<h5 id="another-example">Another Example</h5>
<p>A simple <code>async</code> function to resolve after a specific time.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#008000">// this function resolves after 5 seconds
</span><span style="color:#008000"></span><span style="color:#00f">const</span> resolveFive = (x) => {
<span style="color:#00f">return</span> <span style="color:#00f">new</span> Promise( resolve => {
setTimeout( () => {
resolve(x);
}, 5000);
});
}
<span style="color:#008000">// an async function
</span><span style="color:#008000"></span><span style="color:#00f">const</span> add = async (x) => {
<span style="color:#00f">let</span> a = resolveFive(30);
<span style="color:#00f">let</span> b = resolveFive(40);
<span style="color:#00f">return</span> x + await a + await b;
}
<span style="color:#008000">// testing
</span><span style="color:#008000"></span>
add(20).then( value => {
console.log(value); <span style="color:#008000">// prints 90 after 5 seconds.
</span><span style="color:#008000"></span>})
</code></pre></div><h3 id="but-i-like-promises-">But I like Promises!! :(</h3>
<p>Yeah Promises are super awesome, but here are some things that make these guys thick:</p>
<h4 id="error-handling">Error handling</h4>
<p>With the Async/wait literals, its possible to handle both synchronous and asynchronous errors with the same constructs, compared to using <code>try/catch</code> blocks. Lets compare error handling in Promises vs async/await.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#008000">// Promises....
</span><span style="color:#008000"></span>
<span style="color:#00f">const</span> bookTaxi = () => {
<span style="color:#00f">try</span> {
getAvailableDrivers()
.then( result => {
<span style="color:#00f">const</span> driversInfo = JSON.parse(result) <span style="color:#008000">// this fails and is not tracked
</span><span style="color:#008000"></span> console.log(driversInfo)
})
} <span style="color:#00f">catch</span> (err) {
console.log(err)
}
}
</code></pre></div><p>With async/await</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">const</span> bookTaxi = async () => {
<span style="color:#00f">try</span> {
<span style="color:#008000">// this may fail
</span><span style="color:#008000"></span> <span style="color:#00f">const</span> driversInfo = JSON.parse(await getAvailableDrivers() )
console.log(driversInfo)
} <span style="color:#00f">catch</span>(err) {
console.log(err)
}
}
</code></pre></div><p>The difference between both, is in the async/await part, the catch block will handle parsing errors.</p>
<h4 id="clean-code">Clean code</h4>
<p>We can write much cleaner code (compare the examples from before). Unlike Promises, we didn’t have to use <code>.then()</code> or create anonymous functions to handle responses, etc. This also makes one avoid nested Promises, which can sometimes be a mess.</p>
<h4 id="error-stacks">Error Stacks</h4>
<p>If you call multiple promises in a chain, and an error is thrown somewhere in the chain, the error stack gives no clue of where such error occured.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#008000">// Promise chain
</span><span style="color:#008000"></span><span style="color:#00f">const</span> bookTaxi = () => {
<span style="color:#00f">return</span> checkRides()
.then( () => anotherPromise() )
.then( () => anotherPromise() )
.then( () => anotherPromise() )
<span style="color:#008000">// ...
</span><span style="color:#008000"></span> .then( () => {
<span style="color:#00f">throw</span> <span style="color:#00f">new</span> Error(<span style="color:#a31515">"something went wrong from our end :/"</span>);
})
}
bookTaxi()
.<span style="color:#00f">catch</span>( err => {
console.log(err)
})
</code></pre></div><p>When an error occures from the above, the stack trace is a disaster, you get something like: <code>Errpr: something went wrong from our end :/ at anotherPromise.then.then.then.then (file.js: x:y)</code></p>
<p>The error stack from async/await, points to the function that contains the error:</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">const</span> booxTaxi = async () => {
await anotherPromise()
await anotherPromise()
await anotherPromise()
await anotherPromise()
<span style="color:#00f">throw</span> <span style="color:#00f">new</span> Error(<span style="color:#a31515">"something went wrong :/"</span>);
}
bookTaxi()
.<span style="color:#00f">catch</span>( err => {
console.log(err); <span style="color:#008000">// Error: something went wrong :/ at (file.js: x:x )
</span><span style="color:#008000"></span> })
</code></pre></div><h4 id="conditionals">Conditionals</h4>
<p>You may have code that fetches some data and decides whether to return that or get more details based on the value of that data.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#008000">// Promise
</span><span style="color:#008000"></span><span style="color:#00f">const</span> bookTaxi = () => {
<span style="color:#00f">return</span> getRides()
.then( rides => {
<span style="color:#00f">if</span> ( rides.alreadyBooked ) {
<span style="color:#00f">return</span> getNoneBooked(rides)
.then( moreRides => {
console.log(moreRides)
<span style="color:#00f">return</span> moreRides
})
} <span style="color:#00f">else</span> {
console.log(rides)
<span style="color:#00f">return</span> rides
}
})
}
</code></pre></div><p>The above looks a bit messy, with all the nesting and unstable conditionals. The async/await version is much more readable.</p>
<div class="highlight"><pre style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#00f">const</span> bookTaxi = async () => {
<span style="color:#00f">const</span> rides = await getRides()
<span style="color:#00f">if</span> ( rides.alreadyBooked ) {
<span style="color:#00f">const</span> moreRides = await getNoneBooked(rides)
console.log(moreRides)
<span style="color:#00f">return</span> moreRides
} <span style="color:#00f">else</span> {
console.log(rides)
<span style="color:#00f">return</span> rides
}
}
</code></pre></div><h3 id="conclusion">Conclusion</h3>
<p>We’ve seen some of the ups of this feature, and how it can substitute for Promises.</p>
<p>The async/await feature is one of the best that has been added to JavaScript. There are less syntactical mess met compared to using Promises, and debugging is far more shorter and less tiring.</p>
<p>Did I miss anything? Let me know in the comments :)</p>
</div>
<div>
<br>
<script async type="text/javascript" src="//cdn.carbonads.com/carbon.js?serve=CK7DTK7L&placement=hakaselogsme" id="_carbonads_js"></script>
</div>
<div class="tags">
<ul class="flat">
<li><a href="/tags/javascript">javascript</a></li>
<li><a href="/tags/async/await">async/await</a></li>
</ul>
</div></div>
</div>
<div class="footer wrapper">
<nav class="nav">
<div>2021 © hakaselogs | <a href="https://github.com/knadh/hugo-ink">Ink</a> theme on <a href="https://gohugo.io">Hugo</a></div>
</nav>
</div>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-90124514-1', 'auto');
ga('send', 'pageview');
}
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script>feather.replace()</script>
</body>
</html>