Async + Await
I promise you'll like this talk
Ugh
I'm Wes Bos
Async+Await
Flow Control in JS is Hard
Promises
The Foundation of Async + Await
Promises are an IOU for something that will happen in the future
- AJAX call returning data
- Access to a User's webcam
- Resizing an image
All of these things take time, we simply kick off the process and move along with our lives.
But why do we do it this way?
JavaScript Waits for no one!
Almost Everything Is Asynchronous
Let's say we wanted to do a few things:
- Make Coffee
- Drink Coffee
- Cook Breakfast
- Eat Breakfast
Do you need to finish making coffee before you can Start Breakfast?
Would it make sense to wait until coffee is made and consumed before we even start cooking breakfast?
no!
we want to start one thing, come back to it once it's finished, and deal with the result accordingly!
Christmas Tree Callback Hell
Most new browser APIs are built on Promises
fetch()
Axios
Many, many more
PaymentRequest, getUserMedia(), Web Animation API
It's easy to make your own too!
we get it
Promises are great.
buuuuuuttt
What's the deal with .then()?
It's still kinda callback-y
Any code that needs to come after the promise still needs to be in the final .then() callback
😕😕😕
Async
+
Await
Async + Await still is promises,
but with a really nice syntax
Let's break it down
JavaScript is almost entirely asynchronous / non-blocking
great!
But it's hard to read/write
PHP
JS
😕😕😕
The PHP is easier to read
The JS is more performant
I'm not really happy
Synchronous looking code, without the wait!
How does it work?
1. Mark it as Async
2. await inside your async fn
Best of Both Worlds!
Another Example
Slow...
Why wait for Wes?
Remember, async+await is just promises
Error Handling
A few options
Option #1
Make sure Errors Don't Happen
Why waste dev time on something that should never happen? #ProblemSolved
Option #2
Try / Catch
Wrap that sucker in a safety blanket
Option #3
Higher Order Function
Async Functions can chain a .catch()
Just Live Your Life
Create a HOF
Hot Shot Implicit Return (WHAT)
Create a new function with your HOF
Very Handy in Node & Express!
Normally we'd Handle each possible Error with next()
🤔 But that doesn't cover errors we throw, unhandled errors or syntax errors...
We need to catch all errors and pass along to the next middleware function
Enter HOF
Then we just wrap our routes!
Any unhandled error will simply get passed along to next()
Option #4
Handle The Error When you Call it
Option #5
Node's Unhandled Rejection Event
Node.js will soon exit your process on unhandled rejected promises
It's the Future!
Tips for Starting today
- Write your APIs in Promises
- Use Async + Await for Flow Control
- Convert Older APIs with Promisify
- Choose an Error Handling Strategy
Thanks!
I'm @wesbos