napi-rs/test_module/src/lib.rs

45 lines
1.3 KiB
Rust
Raw Normal View History

2018-04-28 17:26:38 +09:00
#[macro_use]
extern crate napi_rs as napi;
#[macro_use]
extern crate napi_rs_derive;
2018-04-28 17:26:38 +09:00
extern crate futures;
use napi::{Any, CallContext, Env, Error, Object, Result, Status, Value};
2018-04-28 17:26:38 +09:00
register_module!(test_module, init);
fn init(env: &Env, exports: &mut Value<Object>) -> Result<Option<Value<Object>>> {
exports.set_named_property("testSpawn", env.create_function("testSpawn", test_spawn)?)?;
exports.set_named_property("testThrow", env.create_function("testThrow", test_throw)?)?;
2018-04-28 17:26:38 +09:00
Ok(None)
}
2020-04-21 01:20:35 +09:00
#[js_function]
fn test_spawn(ctx: CallContext) -> Result<Value<Object>> {
2020-02-18 22:09:17 +09:00
use futures::executor::ThreadPool;
use futures::StreamExt;
2020-04-21 01:20:35 +09:00
let env = ctx.env;
2020-02-18 22:09:17 +09:00
let pool = ThreadPool::new().expect("Failed to build pool");
let (tx, rx) = futures::channel::mpsc::unbounded::<i32>();
let fut_values = async move {
let fut_tx_result = async move {
(0..200).for_each(|v| {
2020-02-18 22:09:17 +09:00
tx.unbounded_send(v).expect("Failed to send");
})
};
pool.spawn_ok(fut_tx_result);
let fut = rx.map(|v| v * 2).collect::<Vec<i32>>();
let results = fut.await;
println!("Collected result lenght {}", results.len());
Ok(results.len() as u32)
2020-02-18 22:09:17 +09:00
};
2018-04-28 17:26:38 +09:00
env.perform_async_operation(fut_values, |&mut env, len| env.create_uint32(len))
2018-04-28 17:26:38 +09:00
}
2020-04-21 01:20:35 +09:00
#[js_function]
fn test_throw(_ctx: CallContext) -> Result<Value<Any>> {
Err(Error::from_status(Status::GenericFailure))
2018-04-28 17:26:38 +09:00
}