diff --git a/examples/hello_world.rs b/examples/hello_world.rs index 8227d0c..6ae4643 100644 --- a/examples/hello_world.rs +++ b/examples/hello_world.rs @@ -1,9 +1,12 @@ -use std::{collections::HashMap, sync::Arc}; +use std::{collections::HashMap, sync::Arc, thread::sleep, time::Duration}; -use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::responses::{respond_not_found, respond_template}}; +use loadstar::{controller::Controller, entities::request::Url, router::Router, template::Template, utilities::{async_block::run_async, responses::{respond_not_found, respond_template}}}; use maud::html; use tiny_http::Request; +async fn example_async() { + sleep(Duration::from_secs(1)); +} struct MainRouter { routes: HashMap @@ -42,6 +45,7 @@ struct MainController; impl MainController { fn index_route(request: Request) { + run_async(example_async()); respond_template(request, MainTemplate {}) } } diff --git a/src/utilities/async_block.rs b/src/utilities/async_block.rs new file mode 100644 index 0000000..1c6b305 --- /dev/null +++ b/src/utilities/async_block.rs @@ -0,0 +1,12 @@ +use std::future::Future; + + +pub fn run_async(async_operation: impl Future) -> T { + // Use `block_in_place` to ensure runtime is dropped in a blocking context + tokio::task::block_in_place(|| { + // Get the current Tokio runtime handle + let handle = tokio::runtime::Handle::current(); + // Run the async operation using the handle and wait for it to complete + handle.block_on(async_operation) + }) +} diff --git a/src/utilities/mod.rs b/src/utilities/mod.rs index b396b03..ac00999 100644 --- a/src/utilities/mod.rs +++ b/src/utilities/mod.rs @@ -1 +1,2 @@ pub mod responses; +pub mod async_block;