Pieter Hordijk - Twitter - GitHub

What is asynchronous programming

Asynchronous programming is useful in I/O bound tasks. These tasks include (but are not limited to) reading from / writing to the filesystem, querying the database or making HTTP requests to externals websites.

What these all have in common is they take time to complete. While PHP is waiting for these tasks to complete it cannot do other things. This is called blocking or synchronous.

An example of blocking or synchronous code is a PHP script which makes an HTTP request. While the script waits for the response of the server it blocks the execution of the rest of the script as can be seen in the following example.

<?php
echo "Start\n";
echo request("http://httpbin.org/ip"); 3
echo "Output 1\n";
echo "Output 2\n";
echo "Output 3\n";
echo "Output 4\n";
echo "End\n";

In the example above the script calls an external webserver using the request() function which can be a standard curl call, file_get_contents() or any means of making an HTTP request. As you can see the execution of the script is halted for three seconds while doing nothing waiting for the response of the webserver.

Wouldn't it be nice if we could continue running the script while we wait for the response of the webserver instead? This is where asynchronous code comes in.

The next example written in pseudocode leverages non-blocking or asynchronous programming to continue executing the rest of the PHP script while waiting for a task to complete.

<?php
echo "Start\n";
asyncRequest("http://httpbin.org/ip", function($data) { 3
echo $data; 3
}); 3
echo "Output 1\n";
echo "Output 2\n";
echo "Output 3\n";
echo "Output 4\n";
echo "End\n";

The asynchronous example above executes the exact same things as our first synchronous example. The main difference between the two examples is that the first example waits for the request to complete before continuing the script execution. And the last example fires the request to the external webservice and continues running the script without waiting for the response of the external webservice.

To better be able to see the advantage of the asynchronous approach both examples (including the output) are next to eachother below for a side-by-side comparison.

<?php
echo "Start\n";
echo request("http://httpbin.org/ip"); 3
echo "Output 1\n";
echo "Output 2\n";
echo "Output 3\n";
echo "Output 4\n";
echo "End\n";
<?php
echo "Start\n";
asyncRequest("http://httpbin.org/ip", function($data) { 3
echo $data; 3
}); 3
echo "Output 1\n";
echo "Output 2\n";
echo "Output 3\n";
echo "Output 4\n";
echo "End\n";

As you can see a side effect of typical asynchronous code is that the order of execution changes. The lines 9 and 10 are being executed while the script waits for the response of the webserver. In the next / follow up blog post we will see what main approaches there are to asynchronous programming and how we can turn the flow of execution back into a linear one again.