nodejs / help

:sparkles: Need help with Node.js? File an Issue here. :rocket:
1.47k stars 280 forks source link

Wait for a Promise to resolve in c++ #4329

Closed funkyp1ckle closed 2 months ago

funkyp1ckle commented 8 months ago

Details

I am embedding nodejs into a c++ application. I need the result of a asynchronous nodejs function call. I am returned a promise from nodejs. Is there a way to wait for the promise to resolve before continuing the program.

Node.js version

Not applicable.

Example code

v8::EscapableHandleScope escapeHandleScope(isolate); auto checkedCode = v8::String::NewFromUtf8(isolate, source.c_str()).ToLocalChecked(); auto script = v8::Script::Compile(localContext, checkedCode).ToLocalChecked(); v8::TryCatch tryCatch(isolate); auto result = script->Run(localContext).ToLocalChecked(); if (result.IsEmpty()) { std::cerr << "Running Script has unhandled exception" << std::endl; std::cerr << *v8::String::Utf8Value(isolate, tryCatch.Exception()) << std::endl; exit(ErrorCode::PROCESSING_ERROR); } if (result->IsPromise()) { v8::Local promise = result.As(); while (promise->State() == v8::Promise::kPending) { //isolate->PerformMicrotaskCheckpoint(); uv_run(node::GetCurrentEventLoop(isolate), UV_RUN_ONCE); } result = promise->State() == v8::Promise::kFulfilled ? promise->Result() : v8::Local(); } return escapeHandleScope.Escape(result);

Operating system

Windows

Scope

c++ embedding promise

Module and version

libnode

RedYetiDev commented 3 months ago

Hi! Please reformat your question to make use of markdown features, like code blocks, to make it more readable. Thank you!