KEMBAR78
Introducing Async/Await | PDF
Introducing Async/Await
Valeri Karpov
@code_barbarian
github.com/vkarpov15
About Me
● Lead for Mongoose, Node+MongoDB ODM
● Author, Mastering Async/Await (ebook)
● Blogger, thecodebarbarian.com
● Invented the term “MEAN stack”
● 3rd async/await workshop: SF, Zagreb
Workshop Schedule
● 3:00-3:10 Intro, Return Values
● 3:10-3:40 Exercise 1
● 3:40-3:50 Error Handling
● 3:50-4:20 Exercise 2
● 4:20-4:25 Wrap-up and Takeaways
What Is Async/Await?
● 2 new keywords
● Async: special function that returns a promise
● Await: pauses execution of an async function
Callback Hell
● Error handling
● Readability
Async/Await Makes Async Logic Flat
Loops, If Statements, Try/Catch Work
Can Only Await Within An Async Function
TLDR; don’t use forEach() with async/await*
A Brief Overview of Promises
● Promise = state machine
● Represents async op
● Can fulfill with a value
● Or reject with an error
● await only handles promises
Await and Assignment
● Promise fulfilled value
Composing Async Functions
● Async functions return a promise
● Referred to as the returned promise
Resolved Value vs Return Value
The value you return from an async function is
not the return value! Await unwraps the promise
Exercise 1: Gather Blog Post Comments
● Suppose you have an API with 2 endpoints:
○ /post?id=${id}
○ /posts
Exercise 1: Gather Blog Post Comments
● fetch() a list of blog posts
● fetch() the content of each blog post
● Find the id of the first post whose content
contains “async/await hell”
● http://bit.ly/async-await-exercise-1
Part 2: Error Handling
● await on a fulfilled promise returns the value
● await on a rejected promise throws an error
Consolidated Error Handling
● 3 different patterns to handle all CB errors
Consolidated Error Handling
● Async function try/catch handles sync errors
Unhandled Errors Become Rejections
● Throwing rejects the returned promise
Rejected Value vs Sync Error
● Rejected value like resolved value for errors
Await Throws, Not the Function Call
Should You Use Try/Catch?
● catch() works too, often a better choice
Try/Catch vs. catch()
● Try/catch for specific, catch() for general
● Don’t use try/catch to wrap the entire function
Exercise 2: Retrying Failed Requests
● Exercise 1 assumed the API was reliable
● What about if every 2nd request fails?
● Need to wrap fetch() to retry 3 times
● http://bit.ly/async-await-exercise-2
Key Takeaways
● Async functions always return a promise
● return resolves the returned promise
● throw rejects the returned promise
● await pauses execution until promise settles
● await p returns the value p is fulfilled with
Further Reading
● http://bit.ly/node-promises-from-scratch
● http://bit.ly/async-await-design-patterns
● http://bit.ly/node-async-await
● The 80/20 Guide to ES2015 Generators
Thanks for Attending!
The Mastering Async/Await Ebook, June 14, 2018
asyncawait.net/wyncode

Introducing Async/Await