neon/sys/
promise.rs

1//! JavaScript Promise and Deferred handle
2//!
3//! See: [Promises in Node-API](https://nodejs.org/api/n-api.html#n_api_promises)
4
5use std::mem::MaybeUninit;
6
7use super::{bindings as napi, raw::Env};
8
9/// Create a `Promise` and a `napi::Deferred` handle for resolving it
10///
11/// # Safety
12/// * `env` is a valid `napi_env` for the current thread
13/// * The returned `napi::Value` does not outlive `env`
14pub unsafe fn create(env: Env) -> (napi::Deferred, napi::Value) {
15    let mut deferred = MaybeUninit::uninit();
16    let mut promise = MaybeUninit::uninit();
17
18    napi::create_promise(env, deferred.as_mut_ptr(), promise.as_mut_ptr()).unwrap();
19
20    (deferred.assume_init(), promise.assume_init())
21}
22
23/// Resolve a promise from a `napi::Deferred` handle
24///
25/// # Safety
26/// * `env` is a valid `napi_env` for the current thread
27/// * `resolution` is a valid `napi::Value`
28pub unsafe fn resolve(env: Env, deferred: napi::Deferred, resolution: napi::Value) {
29    napi::resolve_deferred(env, deferred, resolution).unwrap();
30}
31
32/// Rejects a promise from a `napi::Deferred` handle
33///
34/// # Safety
35/// * `env` is a valid `napi_env` for the current thread
36/// * `rejection` is a valid `napi::Value`
37pub unsafe fn reject(env: Env, deferred: napi::Deferred, rejection: napi::Value) {
38    napi::reject_deferred(env, deferred, rejection).unwrap();
39}
40
41#[cfg(feature = "napi-6")]
42/// Rejects a promise from a `napi::Deferred` handle with a string message
43///
44/// # Safety
45/// * `env` is a valid `napi_env` for the current thread
46pub unsafe fn reject_err_message(env: Env, deferred: napi::Deferred, msg: impl AsRef<str>) {
47    let msg = super::string(env, msg);
48    let mut err = MaybeUninit::uninit();
49
50    napi::create_error(env, std::ptr::null_mut(), msg, err.as_mut_ptr()).unwrap();
51
52    reject(env, deferred, err.assume_init());
53}