• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef PROMISE_H
17 #define PROMISE_H
18 
19 #include <napi_api.h>
20 
21 /**
22  * @brief Wrap napi promise handling.
23  */
24 class Promise {
25 public:
26     /**
27      * @brief Whether to resolve or reject when settling a promise.
28      */
29     enum class Action : char { RESOLVE, REJECT };
30 
31     /**
32      * @brief Create an object that wraps a JS promise.
33      * @param env The napi environment.
34      * @note Call only from the JS thread.
35      */
36     explicit Promise(napi_env env);
37 
38     /**
39      * @brief Resolve the promise.
40      * @param result The result of the promise.
41      * @return This settled promise as a napi_value.
42      * @note Call only from the JS thread. Further calls to Resolve, Reject or Settle will have no effect.
43      */
44     napi_value Resolve(napi_value result);
45 
46     /**
47      * @brief Reject the promise with a reason for rejecting.
48      * @param reason Why the promise was rejected. An error message to set as result.
49      * @return This settled promise as a napi_value.
50      * @note Call only from the JS thread. Further calls to Resolve, Reject or Settle will have no effect.
51      */
52     napi_value Reject(const BASE_NS::string& reason);
53 
54     /**
55      * @brief Settle the promise.
56      * @param result The result of the promise. Should be a reason string when rejecting.
57      * @param action Whether to resolve or reject the promise.
58      * @return This settled promise as a napi_value.
59      * @note Call only from the JS thread. Further calls to Resolve, Reject or Settle will have no effect.
60      */
61     napi_value Settle(napi_value result, Action action);
62 
63     /**
64      * @brief Get the napi environment.
65      */
66     napi_env Env() const;
67 
68     /**
69      * @brief Return the promise as a napi_value.
70      */
71     napi_value ToNapiValue() const;
72 
73     /**
74      * @brief Return the promise as a napi_value.
75      */
76     operator napi_value() const;
77 
78 private:
79     napi_env env_ { nullptr };
80     napi_deferred deferred_ { nullptr };
81     napi_value promise_ { nullptr };
82     bool alreadySettled_ { false };
83 };
84 
85 #endif
86