• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Calling an ArkTS Method with Return Value of a promise Using Node-API
2<!--Kit: NDK-->
3<!--Subsystem: arkcompiler-->
4<!--Owner: @xliu-huanwei; @shilei123; @huanghello-->
5<!--Designer: @shilei123-->
6<!--Tester: @kirl75; @zsw_zhushiwei-->
7<!--Adviser: @fang-jinxu-->
8
9## When to Use
10You can call the ArkTS APIs, which return a promise, in the created ArkTS runtime environment as follows:
11
12## Calling an ArkTS Method Asynchronously
13Use C++ to call the ArkTS method that returns a promise through the Node-API.
14
15Handle the promise object: Bind the promise object to a C++ callback to process the result returned asynchronously.
16
17Convert the data type: In the callback, convert the JavaScript (JS) result to the data that can be used by C++.
18
19### Sample Code
20- Register the module.
21    ```c++
22    #include "hilog/log.h"
23    #include "napi/native_api.h"
24
25    // Callback for processing a resolved promise.
26    static napi_value ResolvedCallback(napi_env env, napi_callback_info info)
27    {
28        size_t argc = 1;
29        napi_value args[1] = { nullptr };
30        napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
31
32        int result = 0;
33        napi_get_value_int32(env, args[0], &result);
34        OH_LOG_INFO(LOG_APP, "Promise resolved with result:%{public}d", result);
35        return nullptr;
36    }
37
38    // Callback for processing a rejected promise.
39    static napi_value RejectedCallback(napi_env env, napi_callback_info info)
40    {
41        size_t argc = 1;
42        napi_value args[1] = { nullptr };
43        napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
44
45        napi_value error = nullptr;
46        napi_coerce_to_string(env, args[0], &error);
47        char errorMsg[1024];
48        size_t len;
49        napi_get_value_string_utf8(env, error, errorMsg, sizeof(errorMsg), &len);
50        OH_LOG_ERROR(LOG_APP, "Promise rejected with error:%{public}s", errorMsg);
51        return nullptr;
52    }
53
54    static napi_value CallArkTSAsync(napi_env env, napi_callback_info info)
55    {
56        size_t argc = 1;
57        napi_value argv[1] = { nullptr };
58        napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
59        // Initialize the promise object.
60        napi_value promise = nullptr;
61        napi_call_function(env, nullptr, argv[0], 0, nullptr, &promise);
62
63        // Initialize the thenFunc object.
64        napi_value thenFunc = nullptr;
65        if (napi_get_named_property(env, promise, "then", &thenFunc) != napi_ok) {
66            return nullptr;
67        }
68        // Initialize the onResolve object.
69        napi_value onResolve = nullptr;
70        // Initialize the onReject object.
71        napi_value onReject = nullptr;
72        napi_create_function(env, "onResolve", NAPI_AUTO_LENGTH, ResolvedCallback, nullptr, &onResolve);
73        napi_create_function(env, "onReject", NAPI_AUTO_LENGTH, RejectedCallback, nullptr, &onReject);
74        // Create a parameter array.
75        napi_value thenArgv[2] = {onResolve, onReject};
76        napi_call_function(env, promise, thenFunc, 2, thenArgv, nullptr);
77
78        return nullptr;
79    }
80
81    // Register the module.
82    EXTERN_C_START
83    static napi_value Init(napi_env env, napi_value exports)
84    {
85        // Initialize the attribute description array.
86        napi_property_descriptor desc[] = {
87            {"callArkTSAsync", nullptr, CallArkTSAsync, nullptr, nullptr, nullptr, napi_default, nullptr}
88        };
89        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
90        return exports;
91    }
92    EXTERN_C_END
93
94    // Initialize the module.
95    static napi_module nativeModule = {
96        .nm_version = 1,
97        .nm_flags = 0,
98        .nm_filename = nullptr,
99        .nm_register_func = Init,
100        .nm_modname = "entry",
101        .nm_priv = nullptr,
102        .reserved = { 0 },
103    };
104
105    extern "C" __attribute__((constructor)) void RegisterEntryModule()
106    {
107        napi_module_register(&nativeModule);
108    }
109    ```
110
111- Declare APIs.
112    ```ts
113    // index.d.ts
114    export const callArkTSAsync: (func: Function) => object;
115    ```
116
117- Configure the **CMakeLists.txt** file as follows:
118
119    ```
120    // CMakeLists.txt
121    # the minimum version of CMake.
122    cmake_minimum_required(VERSION 3.4.1)
123    project(myapplication)
124
125    set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
126
127    if(DEFINED PACKAGE_FIND_FILE)
128        include(${PACKAGE_FIND_FILE})
129    endif()
130
131    include_directories(${NATIVERENDER_ROOT_PATH}
132                        ${NATIVERENDER_ROOT_PATH}/include)
133
134    add_definitions( "-DLOG_DOMAIN=0xd0d0" )
135    add_definitions( "-DLOG_TAG=\"testTag\"" )
136
137    add_library(entry SHARED napi_init.cpp)
138    target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so)
139    ```
140
141- ArkTS sample code
142    ```ts
143    // index.ets
144    import testNapi from 'libentry.so';
145
146    export function SetTimeout() : Promise<number> {
147        return new Promise((resolve) => {
148            setTimeout(() => {
149                resolve(42);
150            }, 1000);
151        })
152    }
153    testNapi.callArkTSAsync(SetTimeout);
154    ```
155