diff --git a/napi/src/js_values/mod.rs b/napi/src/js_values/mod.rs index d17fc07b..4d4e433c 100644 --- a/napi/src/js_values/mod.rs +++ b/napi/src/js_values/mod.rs @@ -174,11 +174,16 @@ macro_rules! impl_js_value_methods { #[cfg(napi5)] pub fn is_date(&self) -> Result { let mut is_date = true; - let status = unsafe { sys::napi_is_date(self.0.env, self.0.value, &mut is_date) }; - check_status(status)?; + check_status(unsafe { sys::napi_is_date(self.0.env, self.0.value, &mut is_date) })?; Ok(is_date) } + pub fn is_promise(&self) -> Result { + let mut is_promise = true; + check_status(unsafe { sys::napi_is_promise(self.0.env, self.0.value, &mut is_promise) })?; + Ok(is_promise) + } + #[inline] pub fn is_error(&self) -> Result { let mut result = false; diff --git a/test_module/__test__/object.spec.ts b/test_module/__test__/object.spec.ts index 91c2d685..865113e5 100644 --- a/test_module/__test__/object.spec.ts +++ b/test_module/__test__/object.spec.ts @@ -224,3 +224,21 @@ test('testDefineProperties', (t) => { const descriptor = Object.getOwnPropertyDescriptor(obj, 'ro') t.is(descriptor?.value ?? descriptor?.get?.(), 'readonly') }) + +test('is promise', (t) => { + t.false(bindings.testIsPromise(1)) + t.false(bindings.testIsPromise('hello')) + t.false(bindings.testIsPromise({})) + t.false(bindings.testIsPromise(new Date())) + t.false(bindings.testIsPromise(Symbol())) + + t.true(bindings.testIsPromise(Promise.resolve())) + t.true(bindings.testIsPromise(Promise.reject().catch(() => {}))) + t.true( + bindings.testIsPromise( + new Promise((resolve) => { + resolve() + }), + ), + ) +}) diff --git a/test_module/src/object.rs b/test_module/src/object.rs index 63c09e60..fef07abc 100644 --- a/test_module/src/object.rs +++ b/test_module/src/object.rs @@ -158,6 +158,12 @@ fn readonly_getter(ctx: CallContext) -> Result { ctx.env.create_string("readonly") } +#[js_function(1)] +fn test_is_promise(ctx: CallContext) -> Result { + let obj = ctx.get::(0)?; + ctx.env.get_boolean(obj.is_promise()?) +} + pub fn register_js(module: &mut Module) -> Result<()> { module.create_named_method("testSetProperty", test_set_property)?; module.create_named_method("testGetProperty", test_get_property)?; @@ -179,5 +185,7 @@ pub fn register_js(module: &mut Module) -> Result<()> { module.create_named_method("testGetElement", test_get_element)?; module.create_named_method("testDeleteElement", test_delete_element)?; module.create_named_method("testDefineProperties", test_define_properties)?; + + module.create_named_method("testIsPromise", test_is_promise)?; Ok(()) }