Skip to content

Instantly share code, notes, and snippets.

@ricardooooquaresmaaa7
Created June 14, 2025 16:30
Show Gist options
  • Save ricardooooquaresmaaa7/42935db8b6491e3cdb2650328e11181a to your computer and use it in GitHub Desktop.
Save ricardooooquaresmaaa7/42935db8b6491e3cdb2650328e11181a to your computer and use it in GitHub Desktop.
#include "promise_sample.h"
// Structure to hold callback-related data for async work
struct CallbackData {
napi_async_work asyncWork = nullptr; // Handle to async work
napi_deferred deferred = nullptr; // Deferred object for promise
napi_ref callback = nullptr; // (Unused here) Reference to a JS callback function
double args = 0; // Input argument
double result = 0; // Result to return
};
// This function runs in a separate thread and performs the actual computation
static void ExecuteCB(napi_env env, void *data)
{
auto *callbackData = reinterpret_cast<CallbackData *>(data);
// In this example, we just pass the input value as the result
callbackData->result = callbackData->args;
}
// This function runs in the main thread once the async work is complete
static void CompleteCB(napi_env env, napi_status status, void *data)
{
auto *callbackData = reinterpret_cast<CallbackData *>(data);
napi_value result = nullptr;
napi_create_double(env, callbackData->result, &result);
// Resolve or reject the promise based on the result value
if (callbackData->result > 0) {
napi_resolve_deferred(env, callbackData->deferred, result);
} else {
napi_reject_deferred(env, callbackData->deferred, result);
}
// Clean up the async work and free allocated memory
napi_delete_async_work(env, callbackData->asyncWork);
delete callbackData;
}
// This is the native function exposed to JavaScript
// It starts an asynchronous operation and returns a Promise
napi_value asyncWorkPromiseSample(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value args[1];
// Get the arguments passed from JavaScript
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_value promise = nullptr;
napi_deferred deferred = nullptr;
// Create a new promise and get its deferred handle
napi_create_promise(env, &deferred, &promise);
// Allocate and initialize callback data
auto *callbackData = new CallbackData();
callbackData->deferred = deferred;
napi_get_value_double(env, args[0], &callbackData->args);
// Create a string to name the async work
napi_value resourceName = nullptr;
napi_create_string_utf8(env, "AsyncCallback", NAPI_AUTO_LENGTH, &resourceName);
// Create the async work item
napi_create_async_work(env, nullptr, resourceName, ExecuteCB, CompleteCB, callbackData, &callbackData->asyncWork);
// Queue the async work to be executed
napi_queue_async_work(env, callbackData->asyncWork);
// Return the promise to JavaScript
return promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment