Rust/Webassembly/wasm-bindgen - getting values from `js_sys' Promise

拈花ヽ惹草 提交于 2020-12-13 07:47:48

问题


I'm playing with wasm-bindgen ( https://github.com/rustwasm/wasm-bindgen ), just out of curiosity.

While playing with the Navigator (web_sys crate) I stumbled upon this method:

https://docs.rs/web-sys/0.3.36/web_sys/struct.MediaDevices.html#method.enumerate_devices

it returns a Result<Promise, JsValue>..now, I'm new to Rust, and my question is how can I fetch the value of the Promise?

How the Closure::wrap works? How to use it with then method to fetch the results?

I wonder if someone could be so kind to explain me how to deal with Promise

Here an example that returns a Promise:

let window = web_sys::window().expect("no global `window` exists");
let navigator = window.navigator();

if let Ok(devs) = navigator.media_devices() {
   if let Ok(prom) = devs.enumerate_devices() {
        //..??? how to list all devices 
   }
}

All the best, Luca


回答1:


There is official documentation available on the wasm-bindgen site.

In short, you can use wasm_bindgen_futures::JsFuture::from(promise).await? to retrieve the result of the promise and continue working with the usual Rust async functionality.



来源:https://stackoverflow.com/questions/60786667/rust-webassembly-wasm-bindgen-getting-values-from-js-sys-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!