Skip to content

Add then and catch methods to Promise class #1668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions doc/promises.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,47 @@ Rejects the Promise object held by the `Napi::Promise::Deferred` object.

* `[in] value`: The Node-API primitive value with which to reject the `Napi::Promise`.

## Promise Methods

### Then

```cpp
<Promise> Napi::Promise::Then(napi_value onFulfilled, napi_value onRejected) const;
```

Attaches fulfillment and/or rejection handlers to the promise and returns a new promise.

**Parameters:**
* `[in] onFulfilled`: A function to be called when the promise is fulfilled
* `[in] onRejected`: A function to be called when the promise is rejected (optional)

**Returns:** A new `<Promise>` that resolves or rejects based on the handler's result.

**Example:**
```cpp
// Single fulfillment handler
Promise newPromise = existingPromise.Then(fulfillmentHandler);

// Both fulfillment and rejection handlers
Promise chainedPromise = existingPromise.Then(onFulfilled, onRejected);
```

### Catch

```cpp
<Promise> Napi::Promise::Catch(napi_value onRejected) const;
```

Attaches a rejection handler to the promise and returns a new promise.

**Parameters:**
* `[in] onRejected`: A function to be called when the promise is rejected

**Returns:** A new `<Promise>` that handles rejection cases.

**Example:**
```cpp
Promise handledPromise = existingPromise.Catch(rejectionHandler);
```

[`Napi::Object`]: ./object.md
72 changes: 72 additions & 0 deletions napi-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -2813,6 +2813,78 @@ inline void Promise::CheckCast(napi_env env, napi_value value) {

inline Promise::Promise(napi_env env, napi_value value) : Object(env, value) {}

inline MaybeOrValue<Promise> Promise::Then(napi_value onFulfilled) const {
EscapableHandleScope scope(_env);
#ifdef NODE_ADDON_API_ENABLE_MAYBE
MaybeOrValue<Value> thenMethodMaybe = Get("then");
Function thenMethod = thenMethodMaybe.Unwrap().As<Function>();
MaybeOrValue<Value> result = thenMethod.Call(*this, {onFulfilled});
if (result.IsJust()) {
return Just(scope.Escape(result.Unwrap()).As<Promise>());
}
return Nothing<Promise>();
#else
Function thenMethod = Get("then").As<Function>();
MaybeOrValue<Value> result = thenMethod.Call(*this, {onFulfilled});
if (scope.Env().IsExceptionPending()) {
return Promise();
}
return scope.Escape(result).As<Promise>();
#endif
}

inline MaybeOrValue<Promise> Promise::Then(napi_value onFulfilled, napi_value onRejected) const {
EscapableHandleScope scope(_env);
#ifdef NODE_ADDON_API_ENABLE_MAYBE
MaybeOrValue<Value> thenMethodMaybe = Get("then");
Function thenMethod = thenMethodMaybe.Unwrap().As<Function>();
MaybeOrValue<Value> result = thenMethod.Call(*this, {onFulfilled, onRejected});
if (result.IsJust()) {
return Just(scope.Escape(result.Unwrap()).As<Promise>());
}
return Nothing<Promise>();
#else
Function thenMethod = Get("then").As<Function>();
MaybeOrValue<Value> result = thenMethod.Call(*this, {onFulfilled, onRejected});
if (scope.Env().IsExceptionPending()) {
return Promise();
}
return scope.Escape(result).As<Promise>();
#endif
}

inline MaybeOrValue<Promise> Promise::Catch(napi_value onRejected) const {
EscapableHandleScope scope(_env);
#ifdef NODE_ADDON_API_ENABLE_MAYBE
MaybeOrValue<Value> catchMethodMaybe = Get("catch");
Function catchMethod = catchMethodMaybe.Unwrap().As<Function>();
MaybeOrValue<Value> result = catchMethod.Call(*this, {onRejected});
if (result.IsJust()) {
return Just(scope.Escape(result.Unwrap()).As<Promise>());
}
return Nothing<Promise>();
#else
Function catchMethod = Get("catch").As<Function>();
MaybeOrValue<Value> result = catchMethod.Call(*this, {onRejected});
if (scope.Env().IsExceptionPending()) {
return Promise();
}
return scope.Escape(result).As<Promise>();
#endif
}

inline MaybeOrValue<Promise> Promise::Then(const Function& onFulfilled) const {
return Then(static_cast<napi_value>(onFulfilled));
}

inline MaybeOrValue<Promise> Promise::Then(const Function& onFulfilled, const Function& onRejected) const {
return Then(static_cast<napi_value>(onFulfilled), static_cast<napi_value>(onRejected));
}

inline MaybeOrValue<Promise> Promise::Catch(const Function& onRejected) const {
return Catch(static_cast<napi_value>(onRejected));
}

////////////////////////////////////////////////////////////////////////////////
// Buffer<T> class
////////////////////////////////////////////////////////////////////////////////
Expand Down
9 changes: 9 additions & 0 deletions napi.h
Original file line number Diff line number Diff line change
Expand Up @@ -1574,7 +1574,16 @@ class Promise : public Object {

static void CheckCast(napi_env env, napi_value value);

Promise();
Promise(napi_env env, napi_value value);

MaybeOrValue<Promise> Then(napi_value onFulfilled) const;
MaybeOrValue<Promise> Then(napi_value onFulfilled, napi_value onRejected) const;
MaybeOrValue<Promise> Catch(napi_value onRejected) const;

MaybeOrValue<Promise> Then(const Function& onFulfilled) const;
MaybeOrValue<Promise> Then(const Function& onFulfilled, const Function& onRejected) const;
MaybeOrValue<Promise> Catch(const Function& onRejected) const;
};

template <typename T>
Expand Down
73 changes: 73 additions & 0 deletions test/promise.cc
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "napi.h"
#include "test_helper.h"

using namespace Napi;

Expand All @@ -23,6 +24,72 @@ Value PromiseReturnsCorrectEnv(const CallbackInfo& info) {
return Boolean::New(info.Env(), deferred.Env() == info.Env());
}

Value ThenMethodOnFulfilled(const CallbackInfo& info) {
auto deferred = Promise::Deferred::New(info.Env());
Function onFulfilled = info[0].As<Function>();

Promise resultPromise = MaybeUnwrap(deferred.Promise().Then(onFulfilled));

bool isPromise = resultPromise.IsPromise();
deferred.Resolve(Number::New(info.Env(), 42));

Object result = Object::New(info.Env());
result["isPromise"] = Boolean::New(info.Env(), isPromise);
result["promise"] = resultPromise;

return result;
}

Value ThenMethodOnFulfilledOnRejectedResolve(const CallbackInfo& info) {
auto deferred = Promise::Deferred::New(info.Env());
Function onFulfilled = info[0].As<Function>();
Function onRejected = info[1].As<Function>();

Promise resultPromise = MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected));

bool isPromise = resultPromise.IsPromise();
deferred.Resolve(Number::New(info.Env(), 42));

Object result = Object::New(info.Env());
result["isPromise"] = Boolean::New(info.Env(), isPromise);
result["promise"] = resultPromise;

return result;
}

Value ThenMethodOnFulfilledOnRejectedReject(const CallbackInfo& info) {
auto deferred = Promise::Deferred::New(info.Env());
Function onFulfilled = info[0].As<Function>();
Function onRejected = info[1].As<Function>();

Promise resultPromise = MaybeUnwrap(deferred.Promise().Then(onFulfilled, onRejected));

bool isPromise = resultPromise.IsPromise();
deferred.Reject(String::New(info.Env(), "Rejected"));

Object result = Object::New(info.Env());
result["isPromise"] = Boolean::New(info.Env(), isPromise);
result["promise"] = resultPromise;

return result;
}

Value CatchMethod(const CallbackInfo& info) {
auto deferred = Promise::Deferred::New(info.Env());
Function onRejected = info[0].As<Function>();

Promise resultPromise = MaybeUnwrap(deferred.Promise().Catch(onRejected));

bool isPromise = resultPromise.IsPromise();
deferred.Reject(String::New(info.Env(), "Rejected"));

Object result = Object::New(info.Env());
result["isPromise"] = Boolean::New(info.Env(), isPromise);
result["promise"] = resultPromise;

return result;
}

Object InitPromise(Env env) {
Object exports = Object::New(env);

Expand All @@ -31,6 +98,12 @@ Object InitPromise(Env env) {
exports["rejectPromise"] = Function::New(env, RejectPromise);
exports["promiseReturnsCorrectEnv"] =
Function::New(env, PromiseReturnsCorrectEnv);
exports["thenMethodOnFulfilled"] = Function::New(env, ThenMethodOnFulfilled);
exports["thenMethodOnFulfilledOnRejectedResolve"] =
Function::New(env, ThenMethodOnFulfilledOnRejectedResolve);
exports["thenMethodOnFulfilledOnRejectedReject"] =
Function::New(env, ThenMethodOnFulfilledOnRejectedReject);
exports["catchMethod"] = Function::New(env, CatchMethod);

return exports;
}
23 changes: 23 additions & 0 deletions test/promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,27 @@ async function test (binding) {
rejecting.then(common.mustNotCall()).catch(common.mustCall());

assert(binding.promise.promiseReturnsCorrectEnv());

const onFulfilled = (value) => value * 2;
const onRejected = (reason) => reason + '!';

const thenOnFulfilled = binding.promise.thenMethodOnFulfilled(onFulfilled);
assert.strictEqual(thenOnFulfilled.isPromise, true);
const onFulfilledValue = await thenOnFulfilled.promise;
assert.strictEqual(onFulfilledValue, 84);

const thenResolve = binding.promise.thenMethodOnFulfilledOnRejectedResolve(onFulfilled, onRejected);
assert.strictEqual(thenResolve.isPromise, true);
const thenResolveValue = await thenResolve.promise;
assert.strictEqual(thenResolveValue, 84);

const thenRejected = binding.promise.thenMethodOnFulfilledOnRejectedReject(onFulfilled, onRejected);
assert.strictEqual(thenRejected.isPromise, true);
const rejectedValue = await thenRejected.promise;
assert.strictEqual(rejectedValue, 'Rejected!');

const catchMethod = binding.promise.catchMethod(onRejected);
assert.strictEqual(catchMethod.isPromise, true);
const catchValue = await catchMethod.promise;
assert.strictEqual(catchValue, 'Rejected!');
}