-
Notifications
You must be signed in to change notification settings - Fork 0
/
native_async.cc
57 lines (42 loc) · 1.33 KB
/
native_async.cc
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
#include <nan.h>
#include <node.h>
#include <unistd.h>
using namespace v8;
using std::string;
class Work {
friend void WorkAsync (uv_work_t*);
friend void WorkAsyncComplete (uv_work_t*, int);
public:
Work() = default;
~Work() = default;
uv_work_t request;
Persistent<Function> callback;
private:
string data = "";
};
void WorkAsync (uv_work_t *request) {
Work* work = static_cast<Work*>(request->data);
work->data = "done";
sleep(3);
}
void WorkAsyncComplete (uv_work_t *request, int status) {
Nan::HandleScope scope;
Work* work = static_cast<Work*>(request->data);
Local<Value> argv[] = { Nan::New<String>(work->data).ToLocalChecked() };
Local<Function> callback = Nan::New<Function>(work->callback);
Nan::Call(callback, Nan::New<Object>(), 1, argv);
delete work;
}
NAN_METHOD (MethodAsync) {
Isolate* isolate = info.GetIsolate();
Work* work = new Work();
work->request.data = work;
Local<Function> callback = Local<Function>::Cast(info[0]);
work->callback.Reset(isolate, callback);
uv_queue_work(uv_default_loop(), &work->request, WorkAsync, WorkAsyncComplete);
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_MODULE_INIT (init) {
Nan::Set(target, Nan::New("methodAsync").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(MethodAsync)).ToLocalChecked());
}
NODE_MODULE(async, init);