1 /* 2 * Copyright (c) 2024 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 HIDEBUG_ASYNCTASK_H_ 17 #define HIDEBUG_ASYNCTASK_H_ 18 19 #include "napi/native_api.h" 20 21 #include <functional> 22 #include <string> 23 #include <type_traits> 24 25 namespace OHOS { 26 namespace HiviewDFX { 27 28 napi_value CreateErrorMessage(napi_env env, const std::string& msg); 29 30 napi_value CreateErrorMessage(napi_env env, const std::string& errCode, const std::string& msg); 31 32 napi_value CreateUndefined(napi_env env); 33 34 class AsyncTask { 35 public: AsyncTask(const std::string& resourceName)36 explicit AsyncTask(const std::string& resourceName): resourceName_(resourceName) {}; 37 virtual ~AsyncTask() = default; 38 39 template<typename T, typename = typename std::enable_if<std::is_base_of<AsyncTask, T>::value>::type> GetPromise(napi_env env, std::function<void(T*)> setReqParam = [](T*) {})40 static napi_value GetPromise(napi_env env, std::function<void(T*)> setReqParam = [](T*) {}) 41 { 42 napi_value promise = nullptr; 43 T* asyncTask = new (std::nothrow) T(); 44 if (asyncTask == nullptr) { 45 return nullptr; 46 } 47 setReqParam(asyncTask); 48 if (!asyncTask->CreatePromise(env, promise)) { 49 delete asyncTask; 50 return nullptr; 51 } 52 return promise; 53 }; 54 55 protected: 56 napi_async_work worker_ = nullptr; 57 napi_deferred deferred_ = nullptr; 58 std::string resourceName_; 59 virtual void Work(napi_env env) = 0; 60 virtual void Done(napi_env env, napi_status status) = 0; 61 62 private: 63 bool CreatePromise(napi_env env, napi_value& promise); 64 static void ExecuteCallBack(napi_env env, void* data); 65 static void CompletedCallBack(napi_env env, napi_status status, void* data); 66 }; 67 } 68 } 69 70 #endif //HIDEBUG_ASYNCTASK_H_ 71