Crates.io | js-function-promisify |
lib.rs | js-function-promisify |
version | 0.2.1 |
source | src |
created_at | 2021-05-11 22:18:58.973546 |
updated_at | 2021-05-11 23:03:33.74442 |
description | A library for working with js-sys functions as futures |
homepage | https://github.com/emily-curry/js-function-promisify |
repository | https://github.com/emily-curry/js-function-promisify |
max_upload_size | |
id | 396336 |
size | 30,870 |
This package provides utilities for working with js_sys::Function
callbacks in async rust the same way you might in javascript. For example, to wait on a timeout to complete in javascript, one might write:
const promise = new Promise((resolve) => {
window.setTimeout(() => { resolve('Hello future!'); }, 500);
});
const result = await promise;
result === 'Hello future!'; // true
To accomplish the same thing with js-function-promisify
:
let future = Callback::new(|| Ok("Hello future!".into()));
web_sys::window()
.unwrap()
.set_timeout_with_callback_and_timeout_and_arguments_0(
future.as_function().as_ref(),
500)
.unwrap();
let result = future.await; // result: Result<JsValue, JsValue>
assert_eq!(result.unwrap().as_string().unwrap(), "Hello future!"); // 🦀
TODO: Document common ways to use Callback. TODO: Document gotchas, primarily use of Closure::once and deallocation on first call.
Contributions are welcome! Feel free to open an issue if you find a bug or have a feature request. Additionally, feedback on the public API is more than welcome, as this is the first library I've published and I'm still getting a feel for what's idiomatic in rust.
Using wasm-pack
is the easiest way to run the tests in this repository. Those folks have some great documentation on it here and here, but as an example one may run the following to run all tests in the library:
wasm-pack test --headless --firefox