我正在尝试使用带有异步调用的wasm_bindgen实现一个API类。
#![allow(non_snake_case)]
use std::future::Future;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use js_sys::Promise;
use web_sys::{Request, RequestInit, RequestMode, Response};
use wasm_bindgen_futures::future_to_promise;
use crate::fetch_example::*;
#[wasm_bindgen]
#[derive(Debug, Serialize, Deserialize)]
pub struct API {
root: String,
}
#[wasm_bindgen]
impl API {
pub fn new(root: &str) -> Self {
Self {
root: root.to_string(),
}
}
pub fn getVersion(&self) -> Promise {
let url = format!("{}/version", self.root);
future_to_promise(async move {
_request_json(&url, "GET")
})
}
// other methods ...
}
// What is the correct returned type instead of Result<JsValue, JsValue> ???
async fn _request_json(url: &str, method: &str) -> Result<JsValue, JsValue> {
let mut opts = RequestInit::new();
opts.method(method);
opts.mode(RequestMode::Cors);
let request = Request::new_with_str_and_init(&url, &opts)?;
request.headers().set("Accept", "application/json")?;
let window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap();
let json = JsFuture::from(resp.json()?).await?;
Ok(json)
}正如我们所看到的,我将HTTP调用提取到单独的私有函数_request_json中,以避免不同API方法中的代码重复(它们应该是多个,而不仅仅是getVersion )。
我从这里取了一个HTTP调用的基本例子:https://rustwasm.github.io/wasm-bindgen/examples/fetch.html
我还发现,应该在future_to_promise:https://github.com/rustwasm/wasm-bindgen/issues/1858的帮助下实现结构方法的异步调用。
因此,问题在于_request_json**. 返回的类型。我猜错了。**
当我编译这个项目时,我得到了一个错误:
type mismatch resolving `<impl std::future::Future as std::future::Future>::Output == std::result::Result<wasm_bindgen::JsValue, wasm_bindgen::JsValue>`如果我将_request_json的主体复制到future_to_promise中,一切都可以正常工作。
_request_json正确的返回表达式是什么使代码工作?
发布于 2021-03-03 16:21:28
这一建筑:
async move {
_request_json(&url, "GET")
}具有impl Future<Output = impl Future<Output = Result<JsValue, JsValue>>>类型。
你可以这样解决它:
future_to_promise(async move {
_request_json(&url, "GET").await
})也可能是这样的:
future_to_promise(_request_json(&url, "GET"))https://stackoverflow.com/questions/66460420
复制相似问题