The experimental::promise type allows eager execution and
synchronisation of async operations.
auto promise = async_read(
stream, asio::buffer(my_buffer),
asio::experimental::use_promise);
... do other stuff while the read is going on ...
promise.async_wait( // completion the operation
[](error_code ec, std::size_t bytes_read)
{
...
});
Promises can be safely disregarded if the result is no longer required.
Different operations can be combined to either wait for all to complete
or for one to complete (and cancel the rest). For example, to wait for
one to complete:
auto timeout_promise =
timer.async_wait(
asio::experimental::use_promise);
auto read_promise = async_read(
stream, asio::buffer(my_buffer),
asio::experimental::use_promise);
auto promise =
asio::experimental::promise<>::race(
timeout_promise, read_promise);
promise.async_wait(
[](std::variant<error_code, std::tuple<error_code, std::size_t>> v)
{
if (v.index() == 0) {} //timed out
else if (v.index() == 1) // completed in time
});
or to wait for all to complete:
auto write_promise = async_write(
stream, asio::buffer(my_write_buffer),
asio::experimental::use_promise);
auto read_promise = async_read(
stream, asio::buffer(my_buffer),
asio::experimental::use_promise);
auto promise =
asio::experimental::promise<>::all(
write_promise, read_promise);
promise.async_wait(
[](std::tuple<error_code, std::size_t> write_result,
std::tuple<error_code, std::size_t> read_result)
{
});