Example with adapter

This commit is contained in:
K.J. Valencik 2020-12-10 21:19:57 -05:00
parent 77f1ffdf04
commit e503caa2b9
No known key found for this signature in database
GPG Key ID: 35E86CAF5A00982C
6 changed files with 86 additions and 1 deletions

View File

@ -67,5 +67,6 @@ members = [
"test/static",
"test/electron",
"test/dynamic/native",
"test/napi"
"test/napi",
"test/tokio",
]

25
test/tokio/Cargo.toml Normal file
View File

@ -0,0 +1,25 @@
[package]
name = "tokio-test"
version = "0.1.0"
authors = ["The Neon Community <david.herman@gmail.com>"]
license = "MIT"
build = "build.rs"
exclude = ["artifacts.json", "index.node"]
edition = "2018"
[lib]
name = "tokio_test"
crate-type = ["cdylib"]
[build-dependencies]
neon-build = {version = "*", path = "../../crates/neon-build"}
[dependencies]
once_cell = "1"
tokio = { version = "0.3", features = ["rt-multi-thread"] }
[dependencies.neon]
version = "*"
path = "../.."
default-features = false
features = ["default-panic-hook", "napi-runtime", "try-catch-api"]

7
test/tokio/build.rs Normal file
View File

@ -0,0 +1,7 @@
extern crate neon_build;
fn main() {
neon_build::setup(); // must be called in build.rs
// add project-specific build logic here...
}

6
test/tokio/index.js Normal file
View File

@ -0,0 +1,6 @@
'use strict';
const native = require('./index.node');
native.getNum(() => new Promise(resolve => setTimeout(resolve, 1000, 5)));

10
test/tokio/package.json Normal file
View File

@ -0,0 +1,10 @@
{
"name": "tokio-test",
"version": "0.1.0",
"description": "Acceptance test suite for Neon with N-API backend",
"author": "The Neon Community",
"license": "MIT",
"scripts": {
"install": "cargo build -p tokio-test"
}
}

36
test/tokio/src/lib.rs Normal file
View File

@ -0,0 +1,36 @@
use neon::prelude::*;
use once_cell::sync::OnceCell;
use tokio::runtime::Runtime;
static RUNTIME: OnceCell<Runtime> = OnceCell::new();
fn get_num(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let callback = cx.argument::<JsFunction>(0)?;
let this = cx.undefined();
let args = Vec::<Handle<JsValue>>::with_capacity(0);
let promise = callback.call(&mut cx, this, args)?;
let future = promise.to_future_adapter(&mut cx, |mut cx, v| {
v.unwrap_or_else(|_| panic!("Promise rejected"))
.downcast::<JsNumber, _>(&mut cx)
.unwrap()
.value(&mut cx)
});
RUNTIME.get().unwrap().spawn(async {
let n = future.await;
println!("n is {}", n);
});
Ok(cx.undefined())
}
#[neon::main]
fn main(mut cx: ModuleContext) -> NeonResult<()> {
let _ = RUNTIME.get_or_init(|| Runtime::new().unwrap());
cx.export_function("getNum", get_num)?;
Ok(())
}