如何使用neon使类中的方法异步



我正试图用一个用neon和Rust async创建的类来创建这个方法。但我不知道如何为类的方法这样做。例如,我希望将myMethod作为一个异步。

use neon::prelude::*;
pub struct SomeClass{
path: String,
}
declare_types! {
pub class MyClass for SomeClass {
init(mut cx) {
let path = cx.argument::<JsString>(0)?.value(); 
Ok(Predictor {
path: path ,
})
}
method myMethod(mut cx) {
let this = cx.this();
let guard = cx.lock();
let test = this.borrow(&guard).path.unwrap();

let vector = vec![1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3,];
// Iterate over the Rust Vec and map each value in the Vec to the JS array
let js_array = JsArray::new(&mut cx, vector.len() as u32);
for (i, obj) in preds.iter().enumerate() {
let element = cx.number(f64::from(*obj));
js_array.set(&mut cx, i as u32, element).unwrap();
}
Ok(js_array.upcast())
}
}
}
// Export the class
register_module!(mut m, {
// <JsEmployee> tells neon what class we are exporting
// "Employee" is the name of the export that the class is exported as
m.export_class::<myClass>("MyClass")?;
Ok(())
});

这是目前neon中的一个todo。但是,您可以创建一个简单的后台任务,并很容易地将其封装在Promise中。有关示例,请参阅文档。

锈蚀

use neon::prelude::*;
struct BackgroundTask;
impl Task for BackgroundTask {
type Output = i32;
type Error = String;
type JsEvent = JsNumber;
fn perform(&self) -> Result<Self::Output, Self::Error> {
Ok(17)
}
fn complete(self, mut cx: TaskContext, result: Result<Self::Output, Self::Error>) -> JsResult<Self::JsEvent> {
Ok(cx.number(result.unwrap()))
}
}
pub fn perform_async_task(mut cx: FunctionContext) -> JsResult<JsUndefined> {
let f = cx.argument::<JsFunction>(0)?;
BackgroundTask.schedule(f);
Ok(cx.undefined())
}
register_module!(mut m, {
m.export_function("performAsyncTask", perform_async_task)
});

JS-

// ./lib/index.js
const { performAsyncTask } = require("../native");
// Iterate 10,0000 times in background thread
const promisePerformAsyncTask = () => {
return new Promise((resolve, reject) => {
performAsyncTask((err, res) => {
let count = 10;
for (let i = 0; i < 100000; i++) {
count++;
}
console.log(count, "first sum from background thread");
});
});
};

最新更新