Add support for #[wasm_bindgen] on async fn (#1754)

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>`.
This commit is contained in:
Alex Crichton
2019-09-06 13:47:16 -05:00
committed by GitHub
parent 7fd6702c6d
commit 88618116ac
10 changed files with 236 additions and 18 deletions

View File

@ -1,8 +1,6 @@
use js_sys::Promise;
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::future_to_promise;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response};
@ -35,11 +33,7 @@ pub struct Signature {
}
#[wasm_bindgen]
pub fn run() -> Promise {
future_to_promise(run_())
}
async fn run_() -> Result<JsValue, JsValue> {
pub async fn run() -> Result<JsValue, JsValue> {
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);