Asynchronous Programming Patterns in Javascript

Retired

This book is no longer available for sale.

Asynchronous Programming Patterns in Javascript

How to Use Async/Await and Promises to Solve Programming Problems

About the Book

Asynchronous programming is everywhere in Javascript. This is the result of the fundamental choices that define how it works. In other languages, you can use multiple threads and that allows synchronous waiting, a crucial feature missing from Javascript. It is by design single-threaded and a wait operation stops everything, just think of the case where a long calculation freezes the UI.

Without a way to wait for a later result synchronously, Javascript needs to use callbacks. Even simple things like waiting for a given duration requires a function that will be run when the time is up.

You can find this pattern everywhere, as most of the things are asynchronous in nature. Using fetch to make an HTTP call to a server is an async operation. Just like getting information about the available cameras and microphones with the getUserMedia call, as it needs to get permission from the user. Same with reading and writing files. While these have synchronous versions for now, they are terrible for performance. Or want to do some web scraping with Puppeteer? Every single instruction is asynchronous as all of them communicate with a remote process. Or for backend applications, reading or writing data to a database is also inherently async.

And not only that some functions are async but all the other functions that call them need to be async too. A piece of functionality that requires making a network call, for example, is asynchronous, no matter how insignificant that call is compared to what other things the function is doing. Because of this, almost all Javascript applications consist of mostly asynchronous operations.

Over the years, the language got a lot of features that make writing async code easier. Gone are the days of the so-called callback hell where a series of callback-based async calls made the program's structure very hard to understand and easy to inadvertently silence errors.

But asynchronous programming is inherently hard. While the language helps with the syntax to make understanding and writing code easier, asynchronicity introduces a lot of potential errors, most of them so subtle they only occur in special circumstances.

Even though I've been working for many years with asynchronous code, some of the problems in this book took me a week to reach a solution I'm happy with. My goal with this book is that you'll have an easier time when you encounter similar problems by knowing what are the hard parts. This way you won't need to start from zero but you'll have a good idea of what are the roadblocks and the best practices.

This book is divided into two parts.

The first chapter is an introduction to async/await and Promises and how each piece of the async puzzle fit together. The primary focus is async functions as they are the mainstream way to program asynchronously in Javascript. But async/await is a kind of magic without knowing about Promises, so you'll learn about them too.

By the end of the first chapter, you'll have a good understanding of how to use async functions and how they work under the hood.

The second part of the book consists of several common programming tasks and problems. You'll learn when that particular problem is important, how to solve it, and what are the edge cases. This gives you a complete picture so that when you encounter a similar problem you'll know how to approach it.

This book is not meant to be read from cover to cover but to be used as a reference guide. With the patterns described in this book, my hope is that you'll see the underlying difficulty with async programming so when you work on your own solutions you'll know the pitfalls and best practices so you'll end up with more reliable code.

About the Author

Tamás Sallai
Tamás Sallai

Given a task that requires writing software, an expert provides better and more reliable solutions. I write articles and books to help you be that expert.

I'm a software developer focusing mostly on cloud computing and web technologies. I'm especially interested in how to handle edge cases to end up with dependable software. One of my main focus is security and how each part affects the whole system.

I co-author the advancedweb.hu blog where I've published more than a hundred technical articles.

Table of Contents

  • Introduction
    • Structure
  • Getting started with async/await
    • Async functions
      • How to use the Promise
      • The benefits of Promises
      • The await keyword
      • Async function examples
      • Chaining Promises
    • Promises
      • Callbacks
      • The Promise constructor
      • Promise states
      • Result value
    • Error handling
      • Error callback in the Promise constructor
        • Rejecting a Promise
        • Detecting errors
      • Error propagation in Promise chains
  • Parallel and sequential processing
    • Parallel processing with Promise.all
      • Results
      • Errors in Promise.all
    • Early init
  • Returning multiple values
  • Convert between Promises and callbacks
    • Callback styles
      • Node-style callbacks
    • Convert callbacks to Promises
      • Promise constructor
        • Promisified functions
      • util.promisify
      • Usual problems
        • Handle this
        • function.length
    • Convert Promises to callbacks
  • Promise timeouts
    • Promise.race
    • Timeout implementation
      • Clear timeout
      • Error object
  • The async serializer pattern
    • Why await is not a solution
    • A general-purpose solution
  • The async disposer pattern
    • Disposer pattern
  • Retrying async operations
    • Backoff algorithm
      • Exponential backoff
    • Javascript implementation
      • Rejection-based retrying
      • Progress-based retrying
  • Paginating with async generators
    • Pagination
    • A solution with async generators
      • Breaking it down
    • Making it generic
  • Using async functions with postMessage
    • Request-response communication
      • Response identification
        • MessageChannel
      • Error handling
    • Using Promises
  • Collection processing with async functions
    • Async for iteration
    • Async functions with reduce
      • Asynchronous reduce
      • Timing
        • await memo last
        • await memo first
        • When parallelism matters
    • Async functions with map
      • Concurrency
        • Batch processing
        • Parallel processing
        • Sequential processing
    • Async functions with forEach
      • Controlling the timing
        • Waiting for finish
        • Sequential processing
    • Async functions with filter
      • Async filter with map
        • Concurrency
      • Async filter with reduce
        • Sequential processing
    • Async functions with some/every
      • Using an async filter
        • Short-circuiting
      • Async some
      • Async every
      • Parallel processing
  • Common errors
    • Not propagating errors
    • Missing await in try..catch
    • Not checking the return value
    • Not closing resources in case of a rejection
    • Using both the rejection and resolve handlers in one then function
    • Not waiting for an async forEach
  • Glossary
  • About the author

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

Now, this is technically risky for us, since you'll have the book or course files either way. But we're so confident in our products and services, and in our authors and readers, that we're happy to offer a full money back guarantee for everything we sell.

You can only find out how good something is by trying it, and because of our 100% money back guarantee there's literally no risk to do so!

So, there's no reason not to click the Add to Cart button, is there?

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earnedover $13 millionwriting, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub