NAPI-Thread-Safe-Promise
Introduction
NOTE: This package assumes understanding of N-API
To be used in conjunction with the N-API module to call C++ code from JavaScript.
Allows the user to call thread safe promise functions such (resolve, reject) in the C++ code and return a promise to the javascript code.
Usage
- Install the package using node package manager:
npm install napi_thread_safe_promise
- Reference this package's include directory in
binding.gyp
:
'include_dirs': ["<!@(node -p \"require('napi_thread_safe_promise').include\")"],
- Include the header in your code:
#include "promiseWrapper.h"
Note: Currently latest node version has bugs with regards to gyp so use the latest stable version (should be v14.15.3
as of now)
Exception handling
To have the ability for exceptions add the following to binding.gyp
:
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions' ],
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES',
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
},
'msvs_settings': {
'VCCLCompilerTool': { 'ExceptionHandling': 1 },
},
'conditions': [
['OS=="win"', { 'defines': [ '_HAS_EXCEPTIONS=1' ] }]
]
Examples
Async Promise Example (with macro)
Napi::Promise promiseFuncJS(const CallbackInfo& info)
{
return PROMISE(info, {
std::thread([resolve, reject]() {
resolve("test");
resolve("test123");
}).detach();
});
}
Note: if we wish to pass json data to our resolve function we just pass in the json string to the function and parse it in the javascript code
We can use a library like https://github.com/nlohmann/json and use the dump function to accomplish this
Async Promise Example (without using macro)
Napi::Promise promiseFuncJS(const CallbackInfo& info) {
return promiseFuncWrapper(info.Env(),
[&info](resolveFunc resolve, rejectFunc reject) {
std::string arg1 = info[0].As<Napi::String>();
std::thread([resolve, reject, arg1]() {
reject(arg1);
}).detach();
}
);
}
JavaScript code for the code examples above
promiseFuncJS(test)
.then(output => {
console.log(output);
})
.catch(err => {
console.error(err);
});
Contribution
For contribution to this package, create a pull request and the maintainer will look into it.
License
NAPI-Thread-Safe-Promise is licensed under BSD-3-Clause.