Wrapping a Callback-Based API

Learn how to use Boost.Asio for asynchronous I/O, and how to implement a coroutine-based API on top of it using C++20 coroutines.

Asynchronous callback-based API using Boost.Asio

There are many asynchronous APIs based on callbacks. Typically, an asynchronous function takes a callback function provided by the caller. The asynchronous function returns immediately and eventually invokes the callback (completion handler) when the asynchronous function has a computed value or is done waiting for something.

To show what an asynchronous callback-based API can look like, we will peek at a Boost library for asynchronous I/O named Boost.Asio. There is a lot to learn about Boost.Asio, that won’t be covered here; We will only describe the absolute minimum of the Boost code and instead focus on the parts directly related to C++ coroutines.

To make the code fit the pages of the course, the examples assume that the following namespace alias has been defined whenever we use code from Boost.Asio:

Get hands-on with 1400+ tech skills courses.