[OpenHarmony] promise implementation of basic usage of napi

This article is based on the basic usage of [OpenHarmony] napi--HelloWorld .

what is promise

  • promiseIs an object in the javascript language, which can represent the success or failure of an asynchronous operation.
  • promiseThe 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 executed then, 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_promisecreate 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_workcreate an asynchronous task. This interface receives two callback functions , executewhich are called after the executor is ready, and are called after the task execution is completed.completeexecutecomplete
  • We executetry 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 is completedone in it as much as possible. That is to say, we try to avoid executeusing napi_envparameters 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/promiseExecute in the directory node-gyp configure buildand 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 MyPromisemodule implements a hiPromisemethod that will be triggered when the incoming hiPromiseparameter trueis , and will be triggered if the incoming parameter is .promiseresolvefalsereject

References

Introduction to Promise usage on mozilla
Run js code online
Napi official document introduces promise

Guess you like

Origin blog.csdn.net/C2681595858/article/details/127732145