Async + Await
I promise you'll like this talk
I'm Wes Bos
Flow Control in JS is Hard
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?
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?
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
Many, many more
PaymentRequest, getUserMedia(), Web Animation API
It's easy to make your own too!
we get it
Promises are great.
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 still is promises,
but with a really nice syntax
Let's break it down
But it's hard to read/write
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!
Why wait for Wes?
Remember, async+await is just promises
A few options
Make sure Errors Don't Happen
Why waste dev time on something that should never happen? #ProblemSolved
Try / Catch
Wrap that sucker in a safety blanket
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
Then we just wrap our routes!
Any unhandled error will simply get passed along to next()
Handle The Error When you Call it
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