mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-03 16:11:22 +00:00
This commit adds support to attach `#[wasm_bindgen]` on an `async fn` which will change the return value into a `Promise` in JS. This in theory has the exact same semantics as an `async` function in JS where you call it with all the arguments, nothing happens and you get a promise back, and then later the promise actually resolves. This commit also adds a helper trait, `IntoJsResult`, to allow `async` functions with multiple kinds of return values instead of requiring everything to be `Result<JsValue, JsValue>`.
66 lines
1.8 KiB
Rust
66 lines
1.8 KiB
Rust
use serde::{Deserialize, Serialize};
|
|
use wasm_bindgen::prelude::*;
|
|
use wasm_bindgen::JsCast;
|
|
use wasm_bindgen_futures::JsFuture;
|
|
use web_sys::{Request, RequestInit, RequestMode, Response};
|
|
|
|
/// A struct to hold some data from the github Branch API.
|
|
///
|
|
/// Note how we don't have to define every member -- serde will ignore extra
|
|
/// data when deserializing
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Branch {
|
|
pub name: String,
|
|
pub commit: Commit,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Commit {
|
|
pub sha: String,
|
|
pub commit: CommitDetails,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct CommitDetails {
|
|
pub author: Signature,
|
|
pub committer: Signature,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
pub struct Signature {
|
|
pub name: String,
|
|
pub email: String,
|
|
}
|
|
|
|
#[wasm_bindgen]
|
|
pub async fn run() -> Result<JsValue, JsValue> {
|
|
let mut opts = RequestInit::new();
|
|
opts.method("GET");
|
|
opts.mode(RequestMode::Cors);
|
|
|
|
let request = Request::new_with_str_and_init(
|
|
"https://api.github.com/repos/rustwasm/wasm-bindgen/branches/master",
|
|
&opts,
|
|
)?;
|
|
|
|
request
|
|
.headers()
|
|
.set("Accept", "application/vnd.github.v3+json")?;
|
|
|
|
let window = web_sys::window().unwrap();
|
|
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
|
|
|
|
// `resp_value` is a `Response` object.
|
|
assert!(resp_value.is_instance_of::<Response>());
|
|
let resp: Response = resp_value.dyn_into().unwrap();
|
|
|
|
// Convert this other `Promise` into a rust `Future`.
|
|
let json = JsFuture::from(resp.json()?).await?;
|
|
|
|
// Use serde to parse the JSON into a struct.
|
|
let branch_info: Branch = json.into_serde().unwrap();
|
|
|
|
// Send the `Branch` struct back to JS as an `Object`.
|
|
Ok(JsValue::from_serde(&branch_info).unwrap())
|
|
}
|