Async++ unknown
Async (co_await/co_return) code for C++
Loading...
Searching...
No Matches
sync_wait.h
Go to the documentation of this file.
1#pragma once
6#include <asyncpp/fire_and_forget.h>
7#include <future>
8
9namespace asyncpp {
16 template<typename T, typename Awaitable>
17 std::future<T> as_promise(Awaitable&& awaiter)
18 requires(!std::is_void_v<T>)
19 {
20 std::promise<T> promise;
21 auto res = promise.get_future();
22 [](std::decay_t<Awaitable> awaiter, std::promise<T> promise) -> eager_fire_and_forget_task<> {
23 try {
24 promise.set_value(co_await std::move(awaiter));
25 } catch (...) { promise.set_exception(std::current_exception()); }
26 }(std::forward<decltype(awaiter)>(awaiter), std::move(promise));
27 return res;
28 }
29
36 template<typename T, typename Awaitable>
37 std::future<void> as_promise(Awaitable&& awaiter)
38 requires(std::is_void_v<T>)
39 {
40 std::promise<void> promise;
41 auto res = promise.get_future();
42 [](std::decay_t<Awaitable> awaiter, std::promise<void> promise) -> eager_fire_and_forget_task<> {
43 try {
44 co_await std::move(awaiter);
45 promise.set_value();
46 } catch (...) { promise.set_exception(std::current_exception()); }
47 }(std::forward<decltype(awaiter)>(awaiter), std::move(promise));
48 return res;
49 }
50
60 auto as_promise(auto&& awaiter) {
61 return as_promise<typename detail::await_return_type<std::remove_cvref_t<decltype(awaiter)>>::type>(
62 std::forward<decltype(awaiter)>(awaiter));
63 }
64} // namespace asyncpp
Promise type that allows waiting for a result in both synchronous and asynchronous code.
Definition promise.h:124
std::future< T > as_promise(Awaitable &&awaiter)
Execute the given awaitable and return a std::promise representing the call.
Definition sync_wait.h:17