Jeff Lee
@RebootJeff
get comfy & avoid mistakes
Intro to Promises
Who is Jeff?
Full-Stack JavaScriptivore
@RebootJeff
Review of the Basics
You can use the API, but do you understand it?
Pop Quiz
- What does `.then()` return?
- Should you always return a promise within a `.then()`?
- Is it always ok to replace callbacks with promises?
- Is a segment of a Promise chain always async?
- What if the code inside the chain is synchronous?
- How do promises work with async-await?
- What does good Promise-based code look like?
Comman Misteaks
...are the inspiration for this presentation
Some Anti-Patterns
- Nesting promises to create pyramid of doom
- Explicitly returning/resolving a value as the last step of a promise chain
- Attaching .catch to every .then
- Wrapping every callback in an anonymous function when point-free code works fine
More Anti-Patterns (as told by Bluebird)
- Explicit constructor
(Unnecessary promisification) - Old-school `deferred`s
- Handling errors via `.then()`
- Ex: `.then(success, fail)`
Sweet
Helpers
Have you heard the word
...about Bluebird?
Helpers
- .all
- .spread
- .tap / .tapCatch
- .finally
- .return
- .mapSeries
- .cancel
(maybe not so common) - Promise.try
(to wrap synchronous code so it can be part of a Promise chain; it can be caught by `.catch` as well)
Caveat on Helpers
Helpers are not part of the Promise A+ spec
...so by using them, you become more dependent on your Promise library. Co-workers might be familiar with promises in general, but not promise libraries. So they may not understand the helpers.
E.g., it might not be worth using a helper like `.tap` (just use a .then anonymous func with the clear `return`)
Real-World
Practices
Good (maybe even BEST) Practices
- Using .mapSeries to reduce load on requested resource/server
- Error handling
- top-level catch-all (w/o this, promises will "swallow" your errors)
- low-level to catch, log, reformat, then re-throw errors (e.g., proxy an AWS SDK error)
RebootJeff
twitter.com/
github.com/
linkedin.com/in/
Find me at
RebootJeff.com
and...
Questions?
Intro to Promises in JS
By rebootjeff
Intro to Promises in JS
WIP
- 1,020