Search code examples
node.jsrustneon-bindings

performing an async task using neon while passing data from nodejs to rust


I want to use neon to perform an async task from nodejs to rust. I want to call a function from nodejs with some data performAsyncTask(data, (err, result) => {}) and get back a result once rust has finished performing the task.

I looked at a basic async example using neon on their github: https://github.com/neon-bindings/examples/blob/main/async/native/src/lib.rs

Unfortunately, I can't seem to figure out how to access the data from the perform method in the BackgroundTask.

If I get the argument passed in from nodejs this way let arg0 = cx.argument::<JsValue>(0)?;, how can I access that within the perform method of the BackgroundTask?

I appreciate the help!

Thanks!


Solution

  • Since this is executing asynchronously, the result wont be available until after the perform_async_task() has returned. In javascript, you'd normally pass a callback to the function, which is then called when the result is available. Neon provides a specific shortcut to this via the .schedule() method.

    fn schedule(self, callback: Handle<'_, JsFunction>)
    

    The callback passed to .schedule() will be called after the task has completed. There is an example which shows this in: https://github.com/neon-bindings/examples/blob/e7b5e3c4ed35f6c5d84895c2f7e7b06389989b6f/fibonacci-async-task/native/src/lib.rs

    The example shows both a synchronous and asynchronous implementation. The key parts of the async implementation are line 44, which gets the callback argument passed in from JS, and line 47 which passes the callback to the .schedule() function

    43: let n = cx.argument::<JsNumber>(0)?.value() as usize;
    44: let cb = cx.argument::<JsFunction>(1)?;
    45: 
    46: let task = FibonacciTask { argument: n };
    47: task.schedule(cb);
    

    The rest should be handled by neon itself, based on the value returned from .complete() in your task implementation