File: async_worker_persistent.cc

package info (click to toggle)
node-addon-api 8.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,248 kB
  • sloc: cpp: 15,431; javascript: 5,631; ansic: 157; makefile: 7
file content (63 lines) | stat: -rw-r--r-- 1,686 bytes parent folder | download | duplicates (3)
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
#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;
}