本文介绍了Rust/Webassembly/wasm-bindgen - 从 `js_sys' Promise 中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在玩 wasm-bindgen ( https://github.com/rustwasm/wasm-bindgen ),只是出于好奇.

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

在使用 Navigator (web_sys crate) 时,我偶然发现了这个方法:

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

它返回一个 Result ..现在,我是 Rust 的新手,我的问题是如何获取 Promise 的值?

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?

Closure::wrap 如何工作?如何使用 then获取结果的方法?

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

这是一个返回 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
   }
}

一切顺利,卢卡

推荐答案

wasm-bindgen 网站上提供的官方文档.

简而言之,您可以使用 wasm_bindgen_futures::JsFuture::from(promise).await? 来检索承诺的结果并继续使用通常的 Rust async 功能.

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.

这篇关于Rust/Webassembly/wasm-bindgen - 从 `js_sys' Promise 中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 07:37