Skip to content

Commit 532243e

Browse files
committed
feat: add way to block on async to from sync code
Wraps function for futures crate to block on an async task
1 parent 41c4bd2 commit 532243e

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ description = "Wrapper around reqwest for use in both native and wasm"
1414
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
1515

1616
[dependencies]
17+
futures = "0.3.28"
1718
reqwest = { version = "0.12.3", default-features = false }
1819

1920
# For native compilation
@@ -27,7 +28,6 @@ js-sys = { version = "0.3.69", optional = true }
2728
web-sys = { version = "0.3.69", optional = true }
2829

2930
[dev-dependencies]
30-
futures = "0.3.28"
3131
reqwest = { version = "0.12.3" }
3232
wasm-bindgen-test = "0.3.34"
3333

src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,4 +75,6 @@ pub use wrappers::fetch;
7575
#[cfg(feature = "yield_now")]
7676
pub use yield_::yield_now;
7777

78+
pub use wrappers::block_on;
79+
7880
pub use reqwest::Client; // Exported to make it easier to use without a second import and maintain semver

src/wrappers.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,14 @@ where
4343
crate::wasm::fetch(request, on_done);
4444
}
4545

46+
/// Provides a cross platform compatible way to run an async function in a blocking fashion.
47+
/// Intended for use in callbacks as this will block but call backs are not async so we need sync code
48+
pub fn block_on<F>(future: F) -> F::Output
49+
where
50+
F: std::future::Future + Send + 'static,
51+
F::Output: Send + 'static,
52+
{
53+
futures::executor::block_on(future)
54+
}
55+
4656
// TODO 3: Test link in documentation after pushing to main

0 commit comments

Comments
 (0)