1 /* 2 * Copyright (C) 2023 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 NAPI_ASYNC_CALLBACK_H 17 #define NAPI_ASYNC_CALLBACK_H 18 19 #include <map> 20 #include <memory> 21 #include <mutex> 22 #include "napi/native_api.h" 23 #include "napi_async_work.h" 24 25 namespace OHOS { 26 namespace Bluetooth { 27 class NapiCallback; 28 class NapiPromise; 29 class NapiNativeObject; 30 31 struct NapiAsyncCallback { 32 enum class Type { 33 CALLBACK = 1, 34 PROMISE, 35 }; 36 37 void CallFunction(int errCode, const std::shared_ptr<NapiNativeObject> &object); 38 napi_value GetRet(void); 39 40 Type type; 41 napi_env env; 42 std::shared_ptr<NapiCallback> callback = nullptr; 43 std::shared_ptr<NapiPromise> promise = nullptr; 44 }; 45 46 class NapiCallback { 47 public: 48 // napi_value 'callback' shall be type of napi_founction, check it use NapiIsFunction(). 49 NapiCallback(napi_env env, napi_value callback); 50 ~NapiCallback(); 51 52 void CallFunction(const std::shared_ptr<NapiNativeObject> &object); 53 void CallFunction(int errCode, const std::shared_ptr<NapiNativeObject> &object); 54 napi_env GetNapiEnv(void); 55 private: 56 NapiCallback(const NapiCallback &) = delete; 57 NapiCallback &operator=(const NapiCallback &) = delete; 58 NapiCallback(NapiCallback &&) = delete; 59 NapiCallback &operator=(NapiCallback &&) noexcept = delete; 60 61 napi_env env_; 62 napi_ref callbackRef_; 63 }; 64 65 class NapiPromise { 66 public: 67 explicit NapiPromise(napi_env env); 68 ~NapiPromise() = default; 69 70 void ResolveOrReject(int errCode, const std::shared_ptr<NapiNativeObject> &object); 71 void Resolve(napi_value resolution); 72 void Reject(napi_value rejection); 73 napi_value GetPromise(void) const; 74 private: 75 napi_env env_; 76 napi_value promise_; 77 napi_deferred deferred_; 78 }; 79 80 class NapiHandleScope { 81 public: 82 explicit NapiHandleScope(napi_env env); 83 ~NapiHandleScope(); 84 85 private: 86 napi_env env_; 87 napi_handle_scope scope_; 88 }; 89 90 } // namespace Bluetooth 91 } // namespace OHOS 92 #endif // NAPI_ASYNC_CALLBACK_H