neon-bindings / neon

Rust bindings for writing safe and fast native Node.js modules.
https://www.neon-bindings.com/
Apache License 2.0
7.98k stars 282 forks source link

feat(neon): Add tokio async runtime support #1055

Open kjvalencik opened 1 month ago

kjvalencik commented 1 month ago

This adds a private trait Runtime that can be used to implement async executors; it currently only supports tokio.

The code generated for async functions is somewhat large. I would like to move this complexity into a public Neon API. My current thinking is a JsPromise::spawn function that takes a future and a callback and returns a promise.

fn async_add(mut cx: FunctionContext) -> JsResult<JsPromise> {
    let (a, b): (f64, f64) = cx.args()?;
    let fut = async move { a + b };

    JsPromise::spawn(&mut cx, fut, |mut cx, res| Ok(cx.number(res)))
}

This implicitly uses the global runtime and the global Channel. Should there be something lower level that can take these as arguments? We could make a JsPromise::builder that uses them as defaults or we could initially keep it simple and have a spawn that does exactly what the macro needs.

Depends on https://github.com/neon-bindings/neon/pull/1057