Can tokio::runtime be used in wasm?


let rt = tokio::runtime::Runtime::new().unwrap();

This code doesn't work when I try to build wasm.

let rt = tokio::runtime::Runtime::new().unwrap();
   |                              ^^^^^^^ could not find `Runtime` in `runtimе
let rt = tokio::runtime::Runtime::new().unwrap();
    |                     ^^^^^^^ private module

Is it possible to use tokio::runtime in wasm or do I need to look for other ways ? Can I use multithreading ?

I tried to start an asynchronous function with rt.block_on, since the current function is not supposed to be asynchronous, it runs in a separate thread.


  • Tokio does have some support WASM, see WASM support in the docs. You need to enable the rt feature (the full feature doesn't work and causes a compilation failure). However, it does not support multi-threaded runtime (as WASM does not support threads), and therefore does not support Runtime::new(). You need to use tokio::runtime::Builder::new_current_thread() and enable the features you want with the methods (which is currently only time and only on WASI).

    However, you should reconsider if you really need tokio. If you are in the browser, use the browser APIs and wasm-bindgen-futures to interact with JavaScript promises via async/await. If you are on WASI, still tokio provides only minimal support and you may want to look for something else.