1 /*
2 * Copyright (C) 2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "Promise.h"
17
18 #include <napi_api.h>
19
Promise(napi_env env)20 Promise::Promise(napi_env env) : env_(env)
21 {
22 napi_create_promise(env, &deferred_, &promise_);
23 }
24
Resolve(napi_value result)25 napi_value Promise::Resolve(napi_value result)
26 {
27 return Settle(result, Action::RESOLVE);
28 }
29
Reject(const BASE_NS::string & reason)30 napi_value Promise::Reject(const BASE_NS::string& reason)
31 {
32 LOG_E("%s", reason.c_str());
33 return Settle(NapiApi::Env { env_ }.GetString(reason), Action::REJECT);
34 }
35
Settle(napi_value result,Action action)36 napi_value Promise::Settle(napi_value result, Action action)
37 {
38 if (alreadySettled_) {
39 LOG_E("Trying to settle a promise that has already been settled");
40 return promise_;
41 }
42 alreadySettled_ = true;
43
44 if (!result) {
45 napi_get_undefined(env_, &result);
46 }
47 if (action == Action::RESOLVE) {
48 napi_resolve_deferred(env_, deferred_, result);
49 } else {
50 napi_reject_deferred(env_, deferred_, result);
51 }
52 return promise_;
53 }
54
Env() const55 napi_env Promise::Env() const
56 {
57 return env_;
58 }
59
ToNapiValue() const60 napi_value Promise::ToNapiValue() const
61 {
62 return promise_;
63 }
64
operator napi_value() const65 Promise::operator napi_value() const
66 {
67 return promise_;
68 }
69