-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathJsiPromise.cpp
More file actions
60 lines (47 loc) · 2.2 KB
/
JsiPromise.cpp
File metadata and controls
60 lines (47 loc) · 2.2 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
#include "JsiPromise.h"
namespace rnexecutorch {
using namespace facebook;
jsi::Value PromiseVendor::createPromise(
const std::function<void(std::shared_ptr<Promise>)> &function) {
if (runtime_ == nullptr) {
throw std::runtime_error("Runtime was null!");
}
auto &runtime = *runtime_;
auto callInvoker = callInvoker_;
// get Promise constructor
auto promiseCtor = runtime.global().getPropertyAsFunction(runtime, "Promise");
// create a "run" function (first Promise arg)
auto runPromise = jsi::Function::createFromHostFunction(
runtime, jsi::PropNameID::forUtf8(runtime, "runPromise"), 2,
[callInvoker,
function](jsi::Runtime &runtime, const jsi::Value &thisValue,
const jsi::Value *arguments, size_t count) -> jsi::Value {
auto resolveLocal = arguments[0].asObject(runtime).asFunction(runtime);
auto resolve = std::make_shared<jsi::Function>(std::move(resolveLocal));
auto rejectLocal = arguments[1].asObject(runtime).asFunction(runtime);
auto reject = std::make_shared<jsi::Function>(std::move(rejectLocal));
auto resolveWrapper =
[resolve, &runtime, callInvoker](
const std::function<jsi::Value(jsi::Runtime &)> &resolver)
-> void {
callInvoker->invokeAsync([resolve, &runtime, resolver]() -> void {
auto valueShared = std::make_shared<jsi::Value>(resolver(runtime));
resolve->call(runtime, *valueShared);
});
};
auto rejectWrapper = [reject, &runtime, callInvoker](
const std::string &errorMessage) -> void {
callInvoker->invokeAsync([reject, &runtime, errorMessage]() -> void {
auto error = jsi::JSError(runtime, errorMessage);
auto errorShared = std::make_shared<jsi::JSError>(error);
reject->call(runtime, errorShared->value());
});
};
auto promise = std::make_shared<Promise>(resolveWrapper, rejectWrapper);
function(promise);
return jsi::Value::undefined();
});
// return new Promise((resolve, reject) => ...)
return promiseCtor.callAsConstructor(runtime, runPromise);
}
} // namespace rnexecutorch