How do I get a context to manually call poll?

  1. I'm using Rust on wasm, using wasm_bindgen_futures.

  2. I currently have

async fn foo() {

I am interested in calling:

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

manually, but how do I get a mut Context<'_> ?

Create a struct implementing Future and await it.

Or just use futures::future::poll_fn() (or the equivalent unstable function from std, looks like it's going to be stabilized soon).

1 Like

Maybe futures::poll! can help?


Looking at the documentation, a Context can be created from a Waker using Context::from_waker(), a Waker can in turn be created from a RawWaker using Waker:: from_raw(), which can be created using RawWaker::new() from a data pointer and a RawWakerVTable, which is created from function pointers using RawWakerVTable::new(). That involves a lot of unsafe because it's intended to be part of the internals of an async runtime.

If you are just polling it without a runtime and without wanting waking behaviour, you can get a Waker that does nothing using futures::task::noop_waker(). The best option is to use a proper async runtime, such as tokio, and just use the runtime's function for running async functions in a sync context.

EDIT: My answer assumes you are outside of an async context. If you are already in an async context and just need to poll for some reason, @steffahn's solution is the way to go.

1 Like

The Context is fundamentally part of and must be provided by an async runtime. Assuming you're in a synchronous context, you're not going to be able to summon a generally useful Context from thin air.

Here, wasm_bindgen_futures provides an async runtime that calls out to JS Promise.then to integrate with the JS event loop. If you want that behavior, then call spawn_local on a future (perhaps an async {} block) to get into "async world" if you're not already.

If you synchronously need a result, that only makes sense if it doesn't need to wait for an external asynchronous value, if that's the case you can try the various noop waker options to poll, but I don't think it's all that likely to be useful. You should instead try to transform any such synchronous code to be "fire and forget" if you can't figure out a good way to be natively async.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.