source: imaps-frontend/node_modules/@parcel/watcher/src/PromiseRunner.hh

main
Last change on this file was 0c6b92a, checked in by stefan toskovski <stefantoska84@…>, 5 weeks ago

Pred finalna verzija

  • Property mode set to 100644
File size: 2.5 KB
Line 
1#ifndef PROMISE_RUNNER_H
2#define PROMISE_RUNNER_H
3
4#include <node_api.h>
5#include "wasm/include.h"
6#include <napi.h>
7
8using namespace Napi;
9
10class PromiseRunner {
11public:
12 const Env env;
13 Promise::Deferred deferred;
14
15 PromiseRunner(Env env) : env(env), deferred(Promise::Deferred::New(env)) {
16 napi_status status = napi_create_async_work(env, nullptr, env.Undefined(),
17 onExecute, onWorkComplete, this, &work);
18 if (status != napi_ok) {
19 work = nullptr;
20 const napi_extended_error_info *error_info = 0;
21 napi_get_last_error_info(env, &error_info);
22 if (error_info->error_message) {
23 Error::New(env, error_info->error_message).ThrowAsJavaScriptException();
24 } else {
25 Error::New(env).ThrowAsJavaScriptException();
26 }
27 }
28 }
29
30 virtual ~PromiseRunner() {}
31
32 Value queue() {
33 if (work) {
34 napi_status status = napi_queue_async_work(env, work);
35 if (status != napi_ok) {
36 onError(Error::New(env));
37 }
38 }
39
40 return deferred.Promise();
41 }
42
43private:
44 napi_async_work work;
45 std::string error;
46
47 static void onExecute(napi_env env, void *this_pointer) {
48 PromiseRunner* self = (PromiseRunner*) this_pointer;
49 try {
50 self->execute();
51 } catch (std::exception &err) {
52 self->error = err.what();
53 }
54 }
55
56 static void onWorkComplete(napi_env env, napi_status status, void *this_pointer) {
57 PromiseRunner* self = (PromiseRunner*) this_pointer;
58 if (status != napi_cancelled) {
59 HandleScope scope(self->env);
60 if (status == napi_ok) {
61 status = napi_delete_async_work(self->env, self->work);
62 if (status == napi_ok) {
63 if (self->error.size() == 0) {
64 self->onOK();
65 } else {
66 self->onError(Error::New(self->env, self->error));
67 }
68 delete self;
69 return;
70 }
71 }
72 }
73
74 // fallthrough for error handling
75 const napi_extended_error_info *error_info = 0;
76 napi_get_last_error_info(env, &error_info);
77 if (error_info->error_message){
78 self->onError(Error::New(env, error_info->error_message));
79 } else {
80 self->onError(Error::New(env));
81 }
82 delete self;
83 }
84
85 virtual void execute() {}
86 virtual Value getResult() {
87 return env.Null();
88 }
89
90 void onOK() {
91 HandleScope scope(env);
92 Value result = getResult();
93 deferred.Resolve(result);
94 }
95
96 void onError(const Error &e) {
97 deferred.Reject(e.Value());
98 }
99};
100
101#endif
Note: See TracBrowser for help on using the repository browser.