Async DOM event callbacks

I am trying to connect DOM events with web_sys, e.g. in a click handler set_onmousedown() to functions that are async, because they perform REST calls, which are async (uses JavaScript Promises which are mapped to Rust Futures.)

In most web_sys examples this is done using non-asynchronous closures.
async closure are only available in Rust nightly, but i shy away from this because i fear using nightly will open further problems.

Ideally i'd like to register a plain async Rust function, but i don't see how.

Connecting a Function works but Function is !Sync. This means, i can not hold them in e.g. lazy_static and have to recreate them each time an event is triggered.

I don't see a satisfying solution. Any ideas?

You will first need to create a callback closure in Rust that spawns the async task with spawn_local. To then convert this closure to a Function, you will have to wrap it in a Closure and use the JsCast trait.

There is an example of doing something similar to this in the Closure docs - it's written for setInterval not onmousedown but the code should be easily adaptable.

spawn_local() looks like a good solution. Thank you!

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.