wasm-bindgen icon indicating copy to clipboard operation
wasm-bindgen copied to clipboard

Support passing `FnOnce` to JS

Open Pauan opened this issue 6 years ago • 5 comments

Motivation

We currently have support for Closure<FnOnce>, but not passing FnOnce directly to JS.

The Promise::new function currently accepts an FnMut, but the closure will only be called once, so it should be FnOnce instead.

This has practical implications. Right now the wasm-bindgen-futures code looks like this:

let mut future = Some(future);

Promise::new(&mut |resolve, reject| {
    let future = future.take().unwrap_throw();

    ...
})

But if it were FnOnce we could simplify that to this:

Promise::new(move |resolve, reject| {
    ...
})

Pauan avatar Sep 10 '19 13:09 Pauan

FWIW, we have https://docs.rs/wasm-bindgen/0.2.50/wasm_bindgen/closure/struct.Closure.html#method.once

fitzgen avatar Sep 10 '19 17:09 fitzgen

@fitzgen Yeah, I mentioned that above, but that's not what this issue is about.

(Though it might be able to reuse some parts of the implementation of Closure::once)

Pauan avatar Sep 10 '19 18:09 Pauan

Any updates on this?

haze avatar Jul 19 '21 18:07 haze

From the linked item #3550, I wanted to point out that the deeper the nesting of the closures, the uglier this gets from an ownership perspective. Having Promise::new accept an FnOnce resolves a ton of ownership complexity.

I'm curious whether users are typically building JS Promises directly via Promise::new or if they're using Rust futures and then converting them to Promises via wasm_bindgen_futures::future_to_promise?

mwberry avatar Aug 10 '23 03:08 mwberry

Probably most users use future_to_promise() as it's far simpler to use.

daxpedda avatar Aug 10 '23 15:08 daxpedda