1

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!

Paul R
  • 208,748
  • 37
  • 389
  • 560
Timur Ridjanovic
  • 1,002
  • 1
  • 12
  • 18

1 Answers1

4

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

transistor
  • 1,480
  • 1
  • 9
  • 12
  • Unfortunately example is deleted from Git :-( – Alexey Dec 09 '21 at 11:49
  • I updated the broken link to point to a specific commit from when the question was answered, but it's from the "legacy" branch of that crate, so might no longer be accurate. The Cargo.toml file at that commit is for neon_bindings 0.3.3 – transistor Mar 15 '22 at 00:06