1 #include <js_native_api.h>
2 #include "../common.h"
3
4 napi_deferred deferred = NULL;
5
createPromise(napi_env env,napi_callback_info info)6 static napi_value createPromise(napi_env env, napi_callback_info info) {
7 napi_value promise;
8
9 // We do not overwrite an existing deferred.
10 if (deferred != NULL) {
11 return NULL;
12 }
13
14 NODE_API_CALL(env, napi_create_promise(env, &deferred, &promise));
15
16 return promise;
17 }
18
19 static napi_value
concludeCurrentPromise(napi_env env,napi_callback_info info)20 concludeCurrentPromise(napi_env env, napi_callback_info info) {
21 napi_value argv[2];
22 size_t argc = 2;
23 bool resolution;
24
25 NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL));
26 NODE_API_CALL(env, napi_get_value_bool(env, argv[1], &resolution));
27 if (resolution) {
28 NODE_API_CALL(env, napi_resolve_deferred(env, deferred, argv[0]));
29 } else {
30 NODE_API_CALL(env, napi_reject_deferred(env, deferred, argv[0]));
31 }
32
33 deferred = NULL;
34
35 return NULL;
36 }
37
isPromise(napi_env env,napi_callback_info info)38 static napi_value isPromise(napi_env env, napi_callback_info info) {
39 napi_value promise, result;
40 size_t argc = 1;
41 bool is_promise;
42
43 NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, &promise, NULL, NULL));
44 NODE_API_CALL(env, napi_is_promise(env, promise, &is_promise));
45 NODE_API_CALL(env, napi_get_boolean(env, is_promise, &result));
46
47 return result;
48 }
49
50 EXTERN_C_START
Init(napi_env env,napi_value exports)51 napi_value Init(napi_env env, napi_value exports) {
52 napi_property_descriptor descriptors[] = {
53 DECLARE_NODE_API_PROPERTY("createPromise", createPromise),
54 DECLARE_NODE_API_PROPERTY("concludeCurrentPromise", concludeCurrentPromise),
55 DECLARE_NODE_API_PROPERTY("isPromise", isPromise),
56 };
57
58 NODE_API_CALL(env, napi_define_properties(
59 env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors));
60
61 return exports;
62 }
63 EXTERN_C_END
64