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 87When using this API, observe to the following: 88 89- If **napi_create_promise** is called when there is an exception not handled, **napi_pending_exception** will be returned. 90- After calling **napi_create_promise**, always check whether the return value is **napi_ok**. If **deferred** and **promise** are used, the application will crash. 91 92```c++ 93napi_value NapiPromiseDemo(napi_env env, napi_callback_info) 94{ 95 napi_deferred deferred = nullptr; 96 napi_value promise = nullptr; 97 napi_status status = napi_ok; 98 99 napi_throw_error(env, "500", "common error"); 100 101 status = napi_create_promise(env, &deferred, &promise); // If there is an error, return napi_pending_exception with deferred and promise set to nullptr. 102 if (status == napi_ok) { 103 // do something 104 } 105 106 return nullptr; 107} 108``` 109 110### napi_resolve_deferred & napi_reject_deferred 111 112Use **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**. 113 114CPP code: 115 116```cpp 117#include "napi/native_api.h" 118 119static napi_value CreatePromise(napi_env env, napi_callback_info info) 120{ 121 // The deferred object is used to delay the execution of a function for a certain period of time. 122 napi_deferred deferred = nullptr; 123 napi_value promise = nullptr; 124 // Create a Promise object. 125 napi_status status = napi_create_promise(env, &deferred, &promise); 126 if (status != napi_ok) { 127 napi_throw_error(env, nullptr, "Create promise failed"); 128 return nullptr; 129 } 130 //Call napi_is_promise to check whether the object created by napi_create_promise is a Promise object. 131 bool isPromise = false; 132 napi_value returnIsPromise = nullptr; 133 napi_is_promise(env, promise, &isPromise); 134 // Convert the Boolean value to napi_value and return it. 135 napi_get_boolean(env, isPromise, &returnIsPromise); 136 return returnIsPromise; 137} 138 139static napi_value ResolveRejectDeferred(napi_env env, napi_callback_info info) 140{ 141 // Obtain and parse parameters. 142 size_t argc = 3; 143 napi_value args[3] = {nullptr}; 144 napi_get_cb_info(env, info, &argc, args, nullptr, nullptr); 145 // 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. 146 bool status; 147 napi_get_value_bool(env, args[2], &status); 148 // Create a Promise object. 149 napi_deferred deferred = nullptr; 150 napi_value promise = nullptr; 151 napi_status createStatus = napi_create_promise(env, &deferred, &promise); 152 if (createStatus != napi_ok) { 153 napi_throw_error(env, nullptr, "Create promise failed"); 154 return nullptr; 155 } 156 // Set the promise state based on the third parameter. 157 if (status) { 158 napi_resolve_deferred(env, deferred, args[0]); 159 } else { 160 napi_reject_deferred(env, deferred, args[1]); 161 } 162 // Return the Promise object with the state set. 163 return promise; 164} 165``` 166 167API declaration: 168 169```ts 170// index.d.ts 171export const createPromise: () => boolean | void; 172export const resolveRejectDeferred: (resolve: string, reject: string, status: boolean) => Promise<string> | void; 173``` 174 175ArkTS code: 176 177```ts 178import hilog from '@ohos.hilog' 179import testNapi from 'libentry.so' 180 181// Create a promise. Return true if the operation is successful, and return false otherwise. 182hilog.info(0x0000, 'Node-API', 'napi_create_promise %{public}s', testNapi.createPromise()); 183// Call resolveRejectDeferred to resolve or reject the promise and set the promise state. 184// Resolve the promise. The return value is passed to the then function. 185let promiseSuccess: Promise<string> = testNapi.resolveRejectDeferred('success', 'fail', true) as Promise<string>; 186promiseSuccess.then((res) => { 187 hilog.info(0x0000, 'Node-API', 'get_resolve_deferred resolve %{public}s', res) 188}).catch((err: Error) => { 189 hilog.info(0x0000, 'Node-API', 'get_resolve_deferred reject %{public}s', err) 190}) 191// Reject the promise. The return value is passed to the catch function. 192let promiseFail: Promise<string> = testNapi.resolveRejectDeferred('success', 'fail', false) as Promise<string>; 193promiseFail.then((res) => { 194 hilog.info(0x0000, 'Node-API', 'get_resolve_deferred resolve %{public}s', res) 195}).catch((err: Error) => { 196 hilog.info(0x0000, 'Node-API', 'get_resolve_deferred reject %{public}s', err) 197}) 198``` 199 200To 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"**. 201 202```text 203// CMakeLists.txt 204add_definitions( "-DLOG_DOMAIN=0xd0d0" ) 205add_definitions( "-DLOG_TAG=\"testTag\"" ) 206target_link_libraries(entry PUBLIC libhilog_ndk.z.so) 207``` 208