Function quickjs_runtime::runtimefacade_utils::promises::new_resolving_promise
source · [−]pub fn new_resolving_promise<P, R, M>(
q_ctx: &QuickJsRealmAdapter,
producer: P,
mapper: M
) -> Result<JSValueRef, JsError> where
R: Send + 'static,
P: FnOnce() -> Result<R, String> + Send + 'static,
M: FnOnce(&QuickJsRealmAdapter, R) -> Result<JSValueRef, JsError> + Send + 'static,
Expand description
create a new promise with a resolver/mapper the resolver will run in a helper thread and thus get a result asynchronously the resulting value will then be mapped to a JSValueRef by the mapper in the EventQueue the promise which was returned is then resolved with the value which is returned by the mapper
Example
use quickjs_runtime::builder::QuickJsRuntimeBuilder;
use quickjs_runtime::quickjs_utils::{functions, objects, primitives};
use quickjs_runtime::quickjs_utils;
use hirofa_utils::js_utils::Script;
use std::time::Duration;
use quickjs_runtime::runtimefacade_utils::promises;
use quickjs_runtime::quickjsruntimeadapter::QuickJsRuntimeAdapter;
let rt = QuickJsRuntimeBuilder::new().build();
rt.exe_rt_task_in_event_loop(move |q_js_rt| {
let q_ctx = q_js_rt.get_main_context();
// create rust function, please note that using new_native_function_data will be the faster option
let func_ref = functions::new_function_q(q_ctx, "asyncTest", move |q_ctx, _this_ref, _args| {
let prom = promises::new_resolving_promise(q_ctx, ||{
std::thread::sleep(Duration::from_secs(1));
Ok(135)
}, |_ctx, res|{
Ok(primitives::from_i32(res))
});
prom
}, 1).ok().expect("could not create func");
// add func to global scope
let global_ref = quickjs_utils::get_global_q(q_ctx);
objects::set_property_q(q_ctx, &global_ref, "asyncTest", &func_ref).ok()
.expect("could not set prop");;
});
rt.eval_sync(Script::new("test_async.es", "console.log('async test');\n
let p = this.asyncTest(123); \n
console.log('p instanceof Promise = ' + p instanceof Promise);\n
p.then((res) => {\n
console.log('p resolved to ' + res);\n
}).catch((err) => {\n
console.log('p rejected to ' + err);\n
});
")).ok().expect("script failed");
// wait so promise can fullfill
std::thread::sleep(Duration::from_secs(2));