Last active
November 8, 2019 21:15
-
-
Save NickNaso/eb35f072fc79840cc13bcd57b78573eb to your computer and use it in GitHub Desktop.
Pass object to AsyncWorker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<napi.h> | |
| #include <chrono> | |
| #include <thread> | |
| use namespace Napi; | |
| class EchoWorker : public AsyncWorker { | |
| public: | |
| EchoWorker(Function& callback, Object& options, std::string& echo) | |
| : AsyncWorker(callback){ | |
| options(Persistent(options)); | |
| echo(echo); | |
| } | |
| ~EchoWorker() {} | |
| // This code will be executed on the worker thread | |
| void Execute() { | |
| // Need to simulate cpu heavy task | |
| std::this_thread::sleep_for(std::chrono::seconds(1)); | |
| } | |
| void OnOK() { | |
| HandleScope scope(Env()); | |
| Callback().Call({Env().Null(), options.Value(), String::New(Env(), echo)}); | |
| } | |
| private: | |
| ObjectReference options; | |
| std::string echo; | |
| }; | |
| Value Echo(const CallbackInfo& info) { | |
| // You need to validate the arguments here. | |
| Function cb = info[1].As<Function>(); | |
| std::string in = info[0].As<String>(); | |
| Object opts = info[2].As<Object>(); | |
| EchoWorker* wk = new EchoWorker(cb, opts, in); | |
| wk->Queue(); | |
| return info.Env().Undefined(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment