1# Implementing Asynchronous Operations Using Node-API
2
3## Introduction
4
5Node-API provides APIs for implementing asynchronous operations for time-consuming tasks, such as downloading data from network or reading a large file. Different from synchronous operations, asynchronous operations are executed in the background without blocking the main thread. When an asynchronous operation is complete, it will be added to the task queue and executed when the main thread is idle.
6
7## Basic Concepts
8
9**Promise** is an object used to handle asynchronous operations in ArkTS. It has three states: **pending**, **fulfilled**, and **rejected**. The initial state is **pending**, which can be changed to **fulfilled** by **resolve()** and to **rejected** by **reject()**. Once the state is **fulfilled** or **rejected**, the promise state cannot be changed. Read on the following to learn basic concepts related to **Promise**:
10
11- Synchronous: Code is executed line by line in sequence. Each line of code is executed after the previous line of code is executed. During synchronous execution, if an operation takes a long time, the execution of the entire application will be blocked until the operation is complete.
12- Asynchronous: Tasks can be executed concurrently without waiting for the end of the previous task. In ArkTS, common asynchronous operations apply for timers, event listening, and network requests. Instead of blocking subsequent tasks, the asynchronous task uses a callback or promise to process its result.
13- **Promise**: an ArkTS object used to handle asynchronous operations. Generally, it is exposed externally by using **then()**, **catch()**, or **finally()** to custom logic.
14- **deferred**: a utility object associated with the **Promise** object to set **resolve()** and **reject()** of **Promise**. It is used internally to maintain the state of the asynchronous model and set the **resolve()** and **reject()** callbacks.
15- **resolve**: a function used to change the promise state from **pending** to **fulfilled**. The parameters passed to **resolve()** can be obtained from **then()** of the **Promise** object.
16- **reject**: a function used to change the promise state from **pending** to **rejected**. The parameters passed to **reject()** can be obtained from **catch()** of the **Promise** object.
17
18**Promise** allows multiple callbacks to be called in a chain, providing better code readability and a better way to deal with asynchronous operations. The APIs provided by the Node-API module help you flexibly process ArkTS asynchronous operations in C/C++.
19
20## Available APIs
21
22The following table lists the APIs for implementing asynchronous operations using ArkTS promises.   
23| API| Description|
24| -------- | -------- |
25| napi_is_promise | Checks whether a **napi_value** is a **Promise** object.|
26| napi_create_promise | Creates a **Promise** object.|
27| napi_resolve_deferred | Resolves a promise by using the **deferred** object associated with it.|
28| napi_reject_deferred | Rejects a promise by using the **deferred** object associated with it|
29
30## Example
31
32If you are just starting out with Node-API, see [Node-API Development Process](use-napi-process.md). The following demonstrates only the C++ and ArkTS code related to promises.
33
34### napi_is_promise
35
36Use **napi_is_promise** to check whether the given **napi_value** is a **Promise** object.
37
38CPP code:
39
40```cpp
41#include "napi/native_api.h"
42
43static napi_value IsPromise(napi_env env, napi_callback_info info) 
44{
45    napi_value argv[1] = {nullptr};
46    size_t argc = 1;
47    napi_status status;
48    // Obtain the parameters passed in.
49    napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr);
50    bool isPromise = false;
51    // Check whether the given parameter is a Promise object and save the result in the isPromise variable.
52    status = napi_is_promise(env, argv[0], &isPromise);
53    if (status != napi_ok) {
54        napi_throw_error(env, nullptr, "Node-API napi_is_promise failed");
55        return nullptr;
56    }
57    napi_value result = nullptr;
58    // Convert the value of isPromise to the type specified by napi_value, and return it.
59    napi_get_boolean(env, isPromise, &result);
60    return result;
61}
62```
63
64API declaration:
65
66```ts
67// index.d.ts
68export const isPromise: <T>(value: T) => boolean;
69```
70
71ArkTS code:
72
73```ts
74import hilog from '@ohos.hilog'
75import testNapi from 'libentry.so'
76
77let value = Promise.resolve();
78// Return true if the object passed in is a promise; return false otherwise.
79hilog.info(0x0000, 'Node-API', 'napi_is_promise %{public}s', testNapi.isPromise(value));
80hilog.info(0x0000, 'Node-API', 'napi_is_promise string %{public}s', testNapi.isPromise(''));
81```
82
83### napi_create_promise
84
85Use **napi_create_promise** to create a **Promise** object.
86
87### napi_resolve_deferred & napi_reject_deferred
88
89Use **napi_resolve_deferred** to change the promise state from **pending** to **fulfilled**, and use **napi_reject_deferred** to change the promise state from **pending** to **rejected**.
90
91CPP code:
92
93```cpp
94#include "napi/native_api.h"
95
96static napi_value CreatePromise(napi_env env, napi_callback_info info)
97{
98    // The deferred object is used to delay the execution of a function for a certain period of time.
99    napi_deferred deferred = nullptr;
100    napi_value promise = nullptr;
101    // Create a Promise object.
102    napi_status status = napi_create_promise(env, &deferred, &promise);
103    if (status != napi_ok) {
104        napi_throw_error(env, nullptr, "Create promise failed");
105        return nullptr;
106    }
107    //Call napi_is_promise to check whether the object created by napi_create_promise is a Promise object.
108    bool isPromise = false;
109    napi_value returnIsPromise = nullptr;
110    napi_is_promise(env, promise, &isPromise);
111    // Convert the Boolean value to napi_value and return it.
112    napi_get_boolean(env, isPromise, &returnIsPromise);
113    return returnIsPromise;
114}
115
116static napi_value ResolveRejectDeferred(napi_env env, napi_callback_info info) 
117{
118    // Obtain and parse parameters.
119    size_t argc = 3;
120    napi_value args[3] = {nullptr};
121    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
122    // The first parameter is the data to be passed to Resolve(), the second parameter is the data to be passed to reject(), and the third parameter is the Promise state.
123    bool status;
124    napi_get_value_bool(env, args[2], &status);
125    // Create a Promise object.
126    napi_deferred deferred = nullptr;
127    napi_value promise = nullptr;
128    napi_status createStatus = napi_create_promise(env, &deferred, &promise);
129    if (createStatus != napi_ok) {
130        napi_throw_error(env, nullptr, "Create promise failed");
131        return nullptr;
132    }
133    // Set the promise state based on the third parameter.
134    if (status) {
135        napi_resolve_deferred(env, deferred, args[0]);
136    } else {
137        napi_reject_deferred(env, deferred, args[1]);
138    }
139    // Return the Promise object with the state set.
140    return promise;
141}
142```
143
144API declaration:
145
146```ts
147// index.d.ts
148export const createPromise: () => boolean | void;
149export const resolveRejectDeferred: (resolve: string, reject: string, status: boolean) => Promise<string> | void;
150```
151
152ArkTS code:
153
154```ts
155import hilog from '@ohos.hilog'
156import testNapi from 'libentry.so'
157
158// Create a promise. Return true if the operation is successful, and return false otherwise.
159hilog.info(0x0000, 'Node-API', 'napi_create_promise %{public}s', testNapi.createPromise());
160// Call resolveRejectDeferred to resolve or reject the promise and set the promise state.
161// Resolve the promise. The return value is passed to the then function.
162let promiseSuccess: Promise<string> = testNapi.resolveRejectDeferred('success', 'fail', true) as Promise<string>;
163promiseSuccess.then((res) => {
164  hilog.info(0x0000, 'Node-API', 'get_resolve_deferred resolve %{public}s', res)
165}).catch((err: Error) => {
166  hilog.info(0x0000, 'Node-API', 'get_resolve_deferred reject %{public}s', err)
167})
168// Reject the promise. The return value is passed to the catch function.
169let promiseFail: Promise<string> = testNapi.resolveRejectDeferred('success', 'fail', false) as Promise<string>;
170promiseFail.then((res) => {
171  hilog.info(0x0000, 'Node-API', 'get_resolve_deferred resolve %{public}s', res)
172}).catch((err: Error) => {
173  hilog.info(0x0000, 'Node-API', 'get_resolve_deferred reject %{public}s', err)
174})
175```
176
177To print logs in the native CPP, add the following information to the **CMakeLists.txt** file and add the header file by using **#include "hilog/log.h"**.
178
179```text
180// CMakeLists.txt
181add_definitions( "-DLOG_DOMAIN=0xd0d0" )
182add_definitions( "-DLOG_TAG=\"testTag\"" )
183target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
184```
185