1 #include "JsiPromises.h"
2 
3 namespace RNJsi {
4 
Promise(jsi::Runtime & rt,jsi::Function resolve,jsi::Function reject)5 JsiPromises::Promise::Promise(jsi::Runtime &rt, jsi::Function resolve,
6                               jsi::Function reject)
7     : runtime_(rt), resolve_(std::move(resolve)), reject_(std::move(reject)) {}
8 
resolve(const jsi::Value & result)9 void JsiPromises::Promise::resolve(const jsi::Value &result) {
10   resolve_.call(runtime_, result);
11 }
12 
reject(const std::string & message)13 void JsiPromises::Promise::reject(const std::string &message) {
14   jsi::Object error(runtime_);
15   error.setProperty(runtime_, "message",
16                     jsi::String::createFromUtf8(runtime_, message));
17   reject_.call(runtime_, error);
18 }
19 
20 jsi::Value
createPromiseAsJSIValue(jsi::Runtime & rt,PromiseSetupFunctionType && func)21 JsiPromises::createPromiseAsJSIValue(jsi::Runtime &rt,
22                                      PromiseSetupFunctionType &&func) {
23   jsi::Function JSPromise = rt.global().getPropertyAsFunction(rt, "Promise");
24   jsi::Function fn = jsi::Function::createFromHostFunction(
25       rt, jsi::PropNameID::forAscii(rt, "fn"), 2,
26       [func = std::move(func)](jsi::Runtime &rt2, const jsi::Value &thisVal,
27                                const jsi::Value *args, size_t count) {
28         jsi::Function resolve = args[0].getObject(rt2).getFunction(rt2);
29         jsi::Function reject = args[1].getObject(rt2).getFunction(rt2);
30         auto wrapper = std::make_shared<Promise>(rt2, std::move(resolve),
31                                                  std::move(reject));
32         func(rt2, wrapper);
33         return jsi::Value::undefined();
34       });
35 
36   return JSPromise.callAsConstructor(rt, fn);
37 }
38 
39 } // namespace RNJsi
40