blob: 8293355d329776ec58d7081d8097f7fbcfcbda98 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
use std::future::Future;
/// Runs an async function to completion by creating a Tokio runtime
/// and blocking on the future within it.
///
/// # Example
///
/// ```
/// use tokio_wrapper::tokio_run;
///
/// let result = tokio_run(async {
/// // your async code here
/// 42
/// });
/// println!("Result: {}", result);
/// ```
pub fn tokio_run<F, T>(future: F) -> T
where
F: Future<Output = T>,
{
// Create a new Tokio runtime and block on the future
let rt = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
rt.block_on(future)
}
/// A macro that wraps an async expression with `tokio_run`.
///
/// Equivalent to:
/// ```ignore
/// tokio_run(async move { ... })
/// ```
///
/// # Example
///
/// ```
/// use tokio_wrapper::tkr;
///
/// // Instead of:
/// // tokio_run(async move { some_async_fn().await })
/// // Use:
/// let result = tkr! { some_async_fn().await };
/// ```
#[macro_export]
macro_rules! tkr {
($($expr:tt)*) => {
$crate::tokio_wrapper::tokio_run(async move { $($expr)* })
};
}
|