PHP › Asynchronous PHP (ReactPHP & Swoole)

How do coroutines in Swoole let you write asynchronous code using a familiar, synchronous looking coding style?

Intermediate

Answer

Swoole coroutines let you write code that reads like ordinary sequential PHP, such as directly calling a database query and using its result on the next line, while Swoole automatically suspends that coroutine during any blocking operation and resumes other pending coroutines in the meantime, giving you the performance benefits of asynchronous execution without needing to write complex nested callback functions.
Swoole\Coroutine\run(function () {
    $result = Swoole\Coroutine\Http\request('https://api.example.com/data');
    echo $result->body;
});
Real-world example A developer migrating a database heavy PHP application to Swoole writes code that still looks like a normal sequential database query and response, while Swoole automatically handles running many of these coroutines concurrently behind the scenes.

Common follow-ups: What happens if a coroutine encounters an error or exception?;How many concurrent coroutines can a single Swoole process realistically handle?