Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Async Therefore Await

Async Therefore Await

This talk is an introduction to async/await in JavaScript, why it's better than Promises, how it works and how to use it today.

Mohamed Oun

March 15, 2018
Tweet

More Decks by Mohamed Oun

Other Decks in Programming

Transcript

  1. Why even write asynchronous code? • JavaScript is single threaded,

    with lots of processes sharing the same thread • DOM rendering, network requests, your client-side code • They can’t all (and don’t have to) wait for each other
  2. But it’s not so rosy.. • Async code comes with

    added complexity • It’s usually harder to read and reason about • Easy to get into the infamous callback hell with more complex code
  3. How JavaScript handles asynchronous code 1. First, there were callbacks

    2. Then came Promises • .then() and .catch() • Easier to read and understand
  4. Async/Await is ‘syntactic sugar’ over Promises • Use the keyword

    async before your function declaration • Await acts like .then() and pauses the execution until the promise is fulfilled • Looks like synchronous code, but waits in the background, instead of hanging the main thread • We get the performance benefits of asynchronous code and the readability of synchronous code • Best of both worlds!
  5. Because async/await is essentially an abstraction over Promises: • An

    async function is a the same as a function which returns a promise
  6. Because async/await is essentially an abstraction over Promises: • An

    async function that throws an exception is equivalent to a function that returns a rejected Promise
  7. Because async/await is essentially an abstraction over Promises: • You

    can use await Promise.all([]) to run multiple promises in parallel
  8. Top-level await workaround • Top-level (global scope) await doesn’t work

    • You can only await in an async function • But do I call the function I just wrote? • We can use IIFEs to get around that
  9. What if I need to support IE? (Poor you) •

    You can use Babel, specifically babel-preset-env • automatically compiles your code based on the browsers you’re targeting • You can configure it to only include the polyfills and transforms needed for the browsers you support. • Transpiling only what's needed to make your bundles smaller
  10. Resources • Await and Async Explained with Diagrams and Examples

    • async / await in JavaScript - What, Why and How - Fun Fun Function • dotJS 2017 - Wes Bos - Async + Await