This article is based on the basic usage of [OpenHarmony] napi--HelloWorld .
what is promise
promise
Is an object in the javascript language, which can represent the success or failure of an asynchronous operation.promise
The advantage is chained calls. In the past, if you want to do multiple asynchronous operations, it will lead to classic callback hell. With the promise chain call, you can bind the callback to the returned Promise to form a Promise chain.
new Promise((resolve, reject) => {
console.log('初始化');
resolve();
})
.then(() => {
throw new Error('有哪里不对了');
console.log('执行「这个」”');
})
.catch(() => {
console.log('执行「那个」');
})
.then(() => {
console.log('执行「这个」,无论前面发生了什么');
});
- In the above example, the call at initialization assumes
resolve()
that the execution result was successful. Then the first one will be executedthen
, and an exception will be thrown in it , and then this exception will be caught and printed有哪里不对了
by the latter , and then the last one will be executed and printed .catch
执行「那个」
then
执行「这个」,无论前面发生了什么
How to implement promises using napi
It can be divided into three steps:
- First
napi_create_promise
create a promise object and a deferred object through the interface. - Then pass the deferred object to the asynchronous function to complete the asynchronous action.
- The promise object returns directly to the js layer.
- The pseudocode (not executable) is as follows:
// Create the promise.
status = napi_create_promise(env, &myPromise->deferred, &promise);
if (status != napi_ok) {
cout << "create promise failed\n";
return NULL;
}
// Create resource name.
napi_value resource = nullptr;
status = napi_create_string_utf8(env, "hiPromise", NAPI_AUTO_LENGTH, &resource);
if (status != napi_ok) {
cout << "create resource name failed\n";
return nullptr;
}
// Create async work.
status = napi_create_async_work(myPromise->deferred);
// Return the promise to JS
return promise;
In order to achieve asynchrony more conveniently, napi also provides related asynchronous interfaces:
- You can use to
napi_create_async_work
create an asynchronous task. This interface receives two callback functions ,execute
which are called after the executor is ready, and are called after the task execution is completed.complete
execute
complete
- We
execute
try not to call napi-related interfaces in the method, because this may cause it to execute javascript objects or interact with js objects. And the operation that needs to call napi iscomplete
done in it as much as possible. That is to say, we try to avoidexecute
usingnapi_env
parameters in the method to avoid interaction with js. - The pseudocode (not executable) is as follows:
// Create async work.
status = napi_create_async_work(
env, nullptr, resource, Execute, Complete, reinterpret_cast<void *>(myPromise), &myPromise->async_work);
if (status != napi_ok) {
cout << "create async work failed\n";
return nullptr;
}
status = napi_queue_async_work(env, myPromise->async_work);
if (status != napi_ok) {
cout << "queue async work failed\n";
return nullptr;
}
full code
- Full code link:
MyPromise - Compile method:
language-study/napi/promise
Execute in the directorynode-gyp configure build
and compile the c++ code.- Execute the js code
node mypromise.js
, you can see the following print, and stop, press ctrl+c to terminate the program:
Execute recv false
Execute recv true
param true then
param false catch
- Compile, but please refer to [OpenHarmony] napi basics to learn and check whether all the required toolchains are installed.
- The above
MyPromise
module implements ahiPromise
method that will be triggered when the incominghiPromise
parametertrue
is , and will be triggered if the incoming parameter is .promise
resolve
false
reject
References
Introduction to Promise usage on mozilla
Run js code online
Napi official document introduces promise