Skip to content

Commit

Permalink
Move async implementation into macro_internal
Browse files Browse the repository at this point in the history
  • Loading branch information
kjvalencik committed Jul 16, 2024
1 parent 7d97a58 commit a0fe39e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 14 deletions.
15 changes: 1 addition & 14 deletions crates/neon-macros/src/export/function/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,11 @@ pub(super) fn export(meta: meta::Meta, input: syn::ItemFn) -> proc_macro::TokenS

// Generate the call to the original function
let call_body = match meta.kind {
// TODO: Should this be moved inside of Neon in some way?
Kind::Async => quote::quote!(
let rt = match neon::RUNTIME.get(&mut cx) {
Some(rt) => rt,
None => return neon::context::Context::throw_error(&mut cx, "neon::RUNTIME is not initialized"),
};

let (#(#tuple_fields,)*) = cx.args()?;
let ch = neon::context::Context::channel(&mut cx);
let (d, promise) = neon::context::Context::promise(&mut cx);
let fut = #name(#context_arg #(#args),*);

rt.spawn(Box::pin(async move {
let res = fut.await;
let _ = d.try_settle_with(&ch, move |mut cx| #result_extract);
}));

Ok(promise.upcast())
neon::macro_internal::spawn(&mut cx, fut, |mut cx, res| #result_extract)
),
Kind::Normal => quote::quote!(
let (#(#tuple_fields,)*) = cx.args()?;
Expand Down
30 changes: 30 additions & 0 deletions crates/neon/src/macro_internal/futures.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use std::future::Future;

use crate::{
context::{Context, TaskContext},
result::JsResult,
types::JsValue,
};

pub fn spawn<'cx, C, F, S>(cx: &mut C, fut: F, settle: S) -> JsResult<'cx, JsValue>
where
C: Context<'cx>,
F: Future + Send + 'static,
F::Output: Send,
S: FnOnce(TaskContext, F::Output) -> JsResult<JsValue> + Send + 'static,
{
let rt = match crate::RUNTIME.get(cx) {
Some(rt) => rt,
None => return cx.throw_error("neon::RUNTIME is not initialized"),
};

let ch = cx.channel();
let (d, promise) = cx.promise();

rt.spawn(Box::pin(async move {
let res = fut.await;
let _ = d.try_settle_with(&ch, move |cx| settle(cx, res));
}));

Ok(promise.upcast())
}
6 changes: 6 additions & 0 deletions crates/neon/src/macro_internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ use crate::{
types::{extract::TryIntoJs, JsValue},
};

#[cfg(all(feature = "napi-6", feature = "futures"))]
pub use self::futures::spawn;

#[cfg(all(feature = "napi-6", feature = "futures"))]
mod futures;

type Export<'cx> = (&'static str, Handle<'cx, JsValue>);

#[linkme::distributed_slice]
Expand Down

0 comments on commit a0fe39e

Please sign in to comment.