forked from nodejs/node-addon-api
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasyncworker-persistent.cc
More file actions
67 lines (52 loc) · 1.68 KB
/
asyncworker-persistent.cc
File metadata and controls
67 lines (52 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "napi.h"
// A variant of TestWorker wherein destruction is suppressed. That is, instances
// are not destroyed during the `OnOK` callback. They must be explicitly
// destroyed.
using namespace Napi;
namespace {
class PersistentTestWorker : public AsyncWorker {
public:
static PersistentTestWorker* current_worker;
static void DoWork(const CallbackInfo& info) {
bool succeed = info[0].As<Boolean>();
Function cb = info[1].As<Function>();
PersistentTestWorker* worker = new PersistentTestWorker(cb, "TestResource");
current_worker = worker;
worker->SuppressDestruct();
worker->_succeed = succeed;
worker->Queue();
}
static Value GetWorkerGone(const CallbackInfo& info) {
return Boolean::New(info.Env(), current_worker == nullptr);
}
static void DeleteWorker(const CallbackInfo& info) {
(void) info;
delete current_worker;
}
~PersistentTestWorker() {
current_worker = nullptr;
}
protected:
void Execute() override {
if (!_succeed) {
SetError("test error");
}
}
private:
PersistentTestWorker(Function cb,
const char* resource_name)
: AsyncWorker(cb, resource_name) {}
bool _succeed;
};
PersistentTestWorker* PersistentTestWorker::current_worker = nullptr;
} // end of anonymous namespace
Object InitPersistentAsyncWorker(Env env) {
Object exports = Object::New(env);
exports["doWork"] = Function::New(env, PersistentTestWorker::DoWork);
exports.DefineProperty(
PropertyDescriptor::Accessor(env, exports, "workerGone",
PersistentTestWorker::GetWorkerGone));
exports["deleteWorker"] =
Function::New(env, PersistentTestWorker::DeleteWorker);
return exports;
}