Chapter 6. Async

Typical web apps will need to start time-consuming external operations and wait for them to finish. They make queries to databases, which can involve waiting for a server across a network to read from a spinning disk. They might use external APIs, which can involve making HTTP or HTTPS requests across the Internet. These can take a lot of time, and if the app can’t multitask, it will waste time waiting for those operations to finish, as it can’t do anything useful in the meantime.

It gets worse: if a non-multitasking app has multiple time-consuming operations that could be done simultaneously (e.g., two independent database queries), it can’t. It has to wait for one to finish, then start the next and wait for that to finish, and so on. This inefficiency adds up quickly and is tremendously wasteful; for high-traffic web apps, some form of multitasking that gets around these problems is a necessity. Some PHP extensions, like cURL and MySQLi, have support for executing multiple operations at a time, but they don’t interoperate with each other.

In Figure 6-1, for example, the two queries could run in parallel, but with no way to multitask, they must run one at a time.

A timeline
Figure 6-1. Two database queries, without async

Like PHP, Hack doesn’t support multithreading, so web apps in Hack need some other form of multitasking.

That’s the purpose of async. It ...

Get Hack and HHVM now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.