1 /*
2 * Copyright (c) 2022 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 <uv.h>
17
18 #include "js_callback_object.h"
19
20 namespace OHOS {
21 namespace MiscServices {
22 constexpr int32_t MAX_TIMEOUT = 2000;
JSCallbackObject(napi_env env,napi_value callback,std::thread::id threadId)23 JSCallbackObject::JSCallbackObject(napi_env env, napi_value callback, std::thread::id threadId)
24 : env_(env), threadId_(threadId)
25 {
26 napi_create_reference(env, callback, 1, &callback_);
27 }
28
~JSCallbackObject()29 JSCallbackObject::~JSCallbackObject()
30 {
31 if (callback_ != nullptr) {
32 if (threadId_ == std::this_thread::get_id()) {
33 napi_delete_reference(env_, callback_);
34 env_ = nullptr;
35 return;
36 }
37 std::shared_ptr<uv_work_t> work = std::make_shared<uv_work_t>();
38 isDone_ = std::make_shared<BlockData<bool>>(MAX_TIMEOUT, false);
39 work->data = this;
40 uv_loop_s *loop = nullptr;
41 napi_get_uv_event_loop(env_, &loop);
42 uv_queue_work_with_qos(
43 loop, work.get(), [](uv_work_t *work) {},
44 [](uv_work_t *work, int status) {
45 JSCallbackObject *jsObject = static_cast<JSCallbackObject *>(work->data);
46 napi_delete_reference(jsObject->env_, jsObject->callback_);
47 bool isFinish = true;
48 jsObject->isDone_->SetValue(isFinish);
49 },
50 uv_qos_user_initiated);
51 isDone_->GetValue();
52 }
53 env_ = nullptr;
54 }
55 } // namespace MiscServices
56 } // namespace OHOS