Last active
December 15, 2019 21:53
-
-
Save codebytere/72c4ea89d811e22afe2a0922ac65da7a to your computer and use it in GitHub Desktop.
a little example of what you'd need to to to create and resolve a promise off the main thread in Objective-C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <napi.h> | |
Napi::Value NoOp(const Napi::CallbackInfo &info) { | |
return info.Env().Undefined(); | |
} | |
Napi::Promise DoAMacOSNativeThing(const Napi::CallbackInfo &info) { | |
Napi::Env env = info.Env(); | |
Napi::Promise::Deferred deferred = Napi::Promise::Deferred::New(env); | |
Napi::ThreadSafeFunction ts_fn = | |
Napi::ThreadSafeFunction::New(env, Napi::Function::New(env, NoOp), | |
"myCallback", 0, 1, [](Napi::Env) {}); | |
[doANativeMacOSThingWithCompletionBlock completion:^(Data blockData, | |
NSError *error) { | |
// we don't care about noop_cb, we'll never call it (it's what we passed as | |
// Napi::Function::New(env, NoOp) above) | |
auto callback = [=](Napi::Env env, Napi::Function noop_cb, DataType *data) { | |
deferred.Resolve(/* convert your data to a Napi::Value here */); | |
}; | |
// DataType must be a ptr, so convert blockData to determine what you want | |
// to resolve here or pass its address | |
ts_fn.BlockingCall(&blockData, callback); | |
}]; | |
return deferred.Promise(); | |
} | |
Napi::Object Init(Napi::Env env, Napi::Object exports) { | |
exports.Set(Napi::String::New(env, "doAMacOSNativeThing"), | |
Napi::Function::New(env, DoAMacOSNativeThing)); | |
return exports; | |
} | |
NODE_API_MODULE(target_name, Init) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment