Add ability to run async functions in blocking mode
All checks were successful
Cargo Build & Test / Tests (pull_request) Successful in 14s
Cargo Build & Test / check-cargo-version (pull_request) Successful in 6s
Cargo Build & Test / Test publish (pull_request) Successful in 22s

This commit is contained in:
Jan Gleytenhoover 2024-08-21 15:55:25 +02:00
parent 91cc658d86
commit 69d71d6588
Signed by: jank
GPG Key ID: 5269D64BE8F4B6FB
3 changed files with 19 additions and 2 deletions

@ -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<String, fn(Request)>
@ -42,6 +45,7 @@ struct MainController;
impl MainController {
fn index_route(request: Request) {
run_async(example_async());
respond_template(request, MainTemplate {})
}
}

@ -0,0 +1,12 @@
use std::future::Future;
pub fn run_async<T>(async_operation: impl Future<Output = T>) -> 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)
})
}

@ -1 +1,2 @@
pub mod responses;
pub mod async_block;