Skip to content

Commit

Permalink
fix: rip out wait_for because it still blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
c-git committed Jul 16, 2024
1 parent 502e490 commit 3517fa1
Show file tree
Hide file tree
Showing 2 changed files with 0 additions and 52 deletions.
2 changes: 0 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,4 @@ pub use wrappers::fetch;
#[cfg(feature = "yield_now")]
pub use yield_::yield_now;

pub use wrappers::wait_for;

pub use reqwest::Client; // Exported to make it easier to use without a second import and maintain semver
50 changes: 0 additions & 50 deletions src/wrappers.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//! Stores the wrapper functions that can be called from either native or wasm
//! code
use futures::Future;

/// Performs a HTTP requests and calls the given callback when done. NB: Needs
/// to use a callback to prevent blocking on the thread that initiates the
/// fetch. Note: Instead of calling get like in the example you can use post,
Expand Down Expand Up @@ -63,52 +61,4 @@ where
crate::wasm::spawn(future);
}

/// Sometimes needed in callbacks to call async code from the sync context
/// Provides a cross platform compatible way to run an async function in a
/// blocking fashion, but without actually blocking because then the function
/// cannot complete and results in a deadlock.
///
/// # Warning
/// Until a better solution can be found this will result in a busy loop so use
/// sparingly.
#[cfg(not(target_arch = "wasm32"))]
pub fn wait_for<F>(future: F) -> F::Output
where
F: Future + 'static + Send,
F::Output: Send,
{
let (tx, rx) = futures::channel::oneshot::channel();
spawn(async move {
tx.send(future.await)
.unwrap_or_else(|_| eprintln!("failed to send but expected rx to still be available"));
});
wait_for_receiver(rx)
}

#[cfg(target_arch = "wasm32")]
/// dox
pub fn wait_for<F>(future: F) -> F::Output
where
F: Future + 'static,
{
let (tx, rx) = futures::channel::oneshot::channel();
spawn(async move {
tx.send(future.await)
.unwrap_or_else(|_| eprintln!("failed to send but expected rx to still be available"));
});
wait_for_receiver(rx)
}

fn wait_for_receiver<T>(mut rx: futures::channel::oneshot::Receiver<T>) -> T {
loop {
// TODO 4: Is there a better way to do this than a busy loop?
if let Some(x) = rx
.try_recv()
.expect("failed to receive. maybe sender panicked")
{
return x;
}
}
}

// TODO 3: Test link in documentation after pushing to main

0 comments on commit 3517fa1

Please sign in to comment.