Код: Выделить всё
template
auto async_from_awaitable(asio::any_io_executor ex,
asio::awaitable aw,
CompletionToken&& token)
{
using token_type = std::decay_t;
// Materialize the token as an lvalue to satisfy async_initiate on MSVC
token_type tk(std::forward(token));
return asio::async_initiate(
[ex, aw = std::move(aw)](auto&& handler) mutable {
// Spawn the coroutine; on completion, deliver via the handler
asio::co_spawn(
ex,
std::move(aw),
// co_spawn completion for non-void: void(std::exception_ptr, T)
[h = std::forward(handler)]
(std::exception_ptr ep, T value) mutable
{
if (ep) {
try {
std::rethrow_exception(ep);
}
catch (const boost::system::system_error& se) {
std::move(h)(se.code(), T{});
return;
}
catch (...) {
std::move(h)(
make_error_code(boost::system::errc::operation_canceled), T{});
return;
}
}
std::move(h)({}, std::move(value));
}
);
},
tk // pass as lvalue
);
}
asio::awaitable compute_answer(bool success)
{
if (success)
{
co_return 42;
}
else
{
// Create an error_code from the generic category
boost::system::error_code ec =
make_error_code(boost::system::errc::permission_denied);
// Throw as system_error
throw boost::system::system_error(ec, "Access denied while opening file");
}
}
int main()
{
asio::io_context io;
auto ex = io.get_executor();
auto handler = [&context](error_code ec, int value)
{
if (ec)
{
context.logger.debug(awl::format()
Подробнее здесь: [url]https://stackoverflow.com/questions/79836850/using-asioasync-initiate-with-asioco-spawn-and-asioany-io-executor[/url]