2018-04-28 17:26:38 +09:00
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_rs as napi;
|
2020-04-26 21:21:45 +09:00
|
|
|
#[macro_use]
|
|
|
|
extern crate napi_rs_derive;
|
2018-04-28 17:26:38 +09:00
|
|
|
|
2020-04-17 12:54:17 +09:00
|
|
|
extern crate futures;
|
|
|
|
|
2020-04-30 19:31:47 +09:00
|
|
|
use napi::{Any, CallContext, Env, Error, Object, Result, Status, Value};
|
2018-04-28 17:26:38 +09:00
|
|
|
|
|
|
|
register_module!(test_module, init);
|
|
|
|
|
2020-05-06 00:13:23 +09:00
|
|
|
fn init(env: &Env, exports: &mut Value<Object>) -> Result<Option<Value<Object>>> {
|
2020-04-30 19:31:47 +09:00
|
|
|
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]
|
2020-05-06 00:13:23 +09:00
|
|
|
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 {
|
2020-05-06 00:13:23 +09:00
|
|
|
(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);
|
2020-05-06 00:13:23 +09:00
|
|
|
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
|
|
|
|
2020-05-06 00:13:23 +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]
|
2020-05-06 00:13:23 +09:00
|
|
|
fn test_throw(_ctx: CallContext) -> Result<Value<Any>> {
|
|
|
|
Err(Error::from_status(Status::GenericFailure))
|
2018-04-28 17:26:38 +09:00
|
|
|
}
|