feat(napi): implement napi_is_promise

This commit is contained in:
LongYinan 2020-10-10 18:17:32 +08:00
parent 27e11d6723
commit e0d75d1453
No known key found for this signature in database
GPG key ID: A3FFE134A3E20881
3 changed files with 33 additions and 2 deletions

View file

@ -174,11 +174,16 @@ macro_rules! impl_js_value_methods {
#[cfg(napi5)]
pub fn is_date(&self) -> Result<bool> {
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<bool> {
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<bool> {
let mut result = false;

View file

@ -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()
}),
),
)
})

View file

@ -158,6 +158,12 @@ fn readonly_getter(ctx: CallContext) -> Result<JsString> {
ctx.env.create_string("readonly")
}
#[js_function(1)]
fn test_is_promise(ctx: CallContext) -> Result<JsBoolean> {
let obj = ctx.get::<JsObject>(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(())
}