From 231ab09a2045e3f6ee33b292f571e6465d7868c8 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 16:36:17 -0300 Subject: [PATCH 1/3] perf(runtime): check the runtime thread, not its run loop, in the Promise proxy The Promise proxy decided whether to marshal a settlement by comparing CFRunLoopGetCurrent() against the runtime loop, both when a Promise was constructed and when it settled. CFRunLoopGetCurrent() creates a run loop for any thread that has none, so every GCD/NSOperationQueue thread that created or settled a Promise got a run loop allocated just to learn it was not the runtime thread. The binding now exposes isRuntimeThread() (pthread_equal against the runtime thread, captured alongside the runtime loop), and the builtin only calls CFRunLoopGetCurrent() on the runtime thread, once per isolate. --- NativeScript/runtime/PromiseProxy.cpp | 28 +++++++++++------------ NativeScript/runtime/js/promise-proxy.js | 29 ++++++++++++++++-------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/NativeScript/runtime/PromiseProxy.cpp b/NativeScript/runtime/PromiseProxy.cpp index b918245b2..e8ff25469 100644 --- a/NativeScript/runtime/PromiseProxy.cpp +++ b/NativeScript/runtime/PromiseProxy.cpp @@ -1,7 +1,5 @@ #include "PromiseProxy.h" -#include - #include "BuiltinLoader.h" #include "Helpers.h" #include "Runtime.h" @@ -10,29 +8,29 @@ using namespace v8; namespace tns { -// Reports whether the calling thread runs the isolate's runtime loop. That loop -// is where timers fire and is always being pumped, so a promise resolution is -// marshaled back to its creating thread only when that thread is the runtime -// loop; a promise created elsewhere settles on whichever thread resolves it. -static void IsRuntimeRunloopCallback(const FunctionCallbackInfo& args) { +// Reports whether the calling thread is the isolate's runtime thread. That +// thread's run loop is where timers fire and is always being pumped, so a +// promise resolution is marshaled back to its creating thread only when that +// thread is the runtime thread; a promise created elsewhere settles on +// whichever thread resolves it. Don't use CFRunLoopGetCurrent() here: it +// creates a run loop for any thread that lacks one. +static void IsRuntimeThreadCallback(const FunctionCallbackInfo& args) { Runtime* runtime = Runtime::GetRuntime(args.GetIsolate()); - bool isRuntimeLoop = - runtime != nullptr && CFRunLoopGetCurrent() == runtime->RuntimeLoop(); - args.GetReturnValue().Set(isRuntimeLoop); + args.GetReturnValue().Set(runtime != nullptr && runtime->IsOnRuntimeThread()); } void PromiseProxy::Init(v8::Local context) { Isolate* isolate = v8::Isolate::GetCurrent(); - Local isRuntimeRunloop; - bool success = v8::Function::New(context, IsRuntimeRunloopCallback) - .ToLocal(&isRuntimeRunloop); + Local isRuntimeThread; + bool success = v8::Function::New(context, IsRuntimeThreadCallback) + .ToLocal(&isRuntimeThread); tns::Assert(success, isolate); Local binding = Object::New(isolate); success = binding - ->Set(context, tns::ToV8String(isolate, "isRuntimeRunloop"), - isRuntimeRunloop) + ->Set(context, tns::ToV8String(isolate, "isRuntimeThread"), + isRuntimeThread) .FromMaybe(false); tns::Assert(success, isolate); diff --git a/NativeScript/runtime/js/promise-proxy.js b/NativeScript/runtime/js/promise-proxy.js index 406127274..b831ea944 100644 --- a/NativeScript/runtime/js/promise-proxy.js +++ b/NativeScript/runtime/js/promise-proxy.js @@ -1,15 +1,24 @@ // Run a Promise's callbacks on the thread that created it, but only when -// that thread is the runtime loop. A Promise created on a background +// that thread is the runtime thread. A Promise created on a background // thread settles on whichever thread resolves it, because the background // run loop may be dormant and marshaling a resolution to it would hang. -const { isRuntimeRunloop } = binding; +// +// Never call CFRunLoopGetCurrent() off the runtime thread: it creates a run +// loop for any thread that lacks one. +const { isRuntimeThread } = binding; const { FunctionPrototypeBind, Proxy } = primordials; +// The runtime loop never changes for an isolate, so it is fetched once, on +// the runtime thread, the first time a Promise is created there. +let runtimeLoop; + global.Promise = new Proxy(global.Promise, { construct: function(target, args) { let origFunc = args[0]; - let runloop = CFRunLoopGetCurrent(); - let originIsRuntimeLoop = isRuntimeRunloop(); + const originIsRuntimeThread = isRuntimeThread(); + if (originIsRuntimeThread && runtimeLoop === undefined) { + runtimeLoop = CFRunLoopGetCurrent(); + } let promise = new target(function(resolve, reject) { function isFulfilled() { @@ -25,12 +34,12 @@ global.Promise = new Proxy(global.Promise, { return; } const resolveCall = FunctionPrototypeBind(resolve, this, value); - if (!originIsRuntimeLoop || runloop === CFRunLoopGetCurrent()) { + if (!originIsRuntimeThread || isRuntimeThread()) { markFulfilled(); resolveCall(); } else { - CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, resolveCall); - CFRunLoopWakeUp(runloop); + CFRunLoopPerformBlock(runtimeLoop, kCFRunLoopDefaultMode, resolveCall); + CFRunLoopWakeUp(runtimeLoop); markFulfilled(); } }, reason => { @@ -38,12 +47,12 @@ global.Promise = new Proxy(global.Promise, { return; } const rejectCall = FunctionPrototypeBind(reject, this, reason); - if (!originIsRuntimeLoop || runloop === CFRunLoopGetCurrent()) { + if (!originIsRuntimeThread || isRuntimeThread()) { markFulfilled(); rejectCall(); } else { - CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, rejectCall); - CFRunLoopWakeUp(runloop); + CFRunLoopPerformBlock(runtimeLoop, kCFRunLoopDefaultMode, rejectCall); + CFRunLoopWakeUp(runtimeLoop); markFulfilled(); } }); From f1be618c74dcd01871a7a9da42236dea34241c8a Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 17:00:45 -0300 Subject: [PATCH 2/3] perf(runtime): settle Promises through the event loop; thread checks over run-loop checks The Promise proxy marshaled runtime-thread settlements with CFRunLoopPerformBlock, which converted every bound resolve/reject into an ObjC block and kept a CFRunLoopRef wrapper per Promise. The builtin now queues settlements in a JS FIFO, and a native postToRuntimeThread() posts a capture-free internal-lane entry per settlement that runs the oldest one on the runtime thread. The builtin no longer touches CFRunLoop at all. Settlements now run in common modes (during UI tracking too), one per run-loop pass, each followed by the lane's microtask checkpoint. The other "is this the runtime thread" checks that compared CFRunLoopGetCurrent() against a stored loop are now thread checks too: ClassBuilder's retain/release hooks and GetNapiEnvIfAlive use Runtime::IsOnRuntimeThread(), and NapiEnv/threadsafe functions use a pthread_threadid_np id, which is never reused, so the tsfn no longer retains the run loop to keep its identity stable. Runtime::RuntimeLoop() and NapiEnv::RuntimeLoop() are gone, along with the vacuous RuntimeLoop() != nullptr guards. --- NativeScript/napi/NapiEnv.h | 18 +++-- NativeScript/napi/NapiEnv.mm | 2 +- NativeScript/napi/NapiThreadSafeFunction.mm | 26 ++----- NativeScript/napi/NodeApiEmbed.mm | 9 +-- NativeScript/runtime/ClassBuilder.mm | 6 +- NativeScript/runtime/PromiseProxy.cpp | 79 +++++++++++++++------ NativeScript/runtime/Runtime.h | 2 - NativeScript/runtime/Runtime.mm | 10 +-- NativeScript/runtime/js/promise-proxy.js | 55 +++++++++----- TestRunner/app/tests/Promises.js | 31 ++++++++ 10 files changed, 156 insertions(+), 82 deletions(-) diff --git a/NativeScript/napi/NapiEnv.h b/NativeScript/napi/NapiEnv.h index 855ceeb6a..c7bcfa071 100644 --- a/NativeScript/napi/NapiEnv.h +++ b/NativeScript/napi/NapiEnv.h @@ -10,7 +10,7 @@ #define NODE_API_EXPERIMENTAL_NO_WARNING #endif -#include +#include #include #include @@ -58,9 +58,17 @@ class NapiEnv : public napi_env__ { v8::Local PrivateKey(NapiPrivateKeySlot slot); - // The runloop of the thread that owns this env — identity checks only - // (is-this-the-env's-thread); work is posted through GetEventLoop(). - CFRunLoopRef RuntimeLoop() const { return runtimeLoop_; } + // System-wide id of the thread that owns this env (pthread_threadid_np). + // Unlike a pthread_t it is never reused after the thread exits, so it stays + // safe to compare against from a producer that outlives the env's thread. + // Work is posted through GetEventLoop(). + uint64_t ThreadId() const { return threadId_; } + bool IsOnEnvThread() const { return CurrentThreadId() == threadId_; } + static uint64_t CurrentThreadId() { + uint64_t id = 0; + pthread_threadid_np(nullptr, &id); + return id; + } // The runtime's event loop, or null once ~Runtime released it. Between // Shutdown and that release it is still returned, and posts to it are @@ -88,7 +96,7 @@ class NapiEnv : public napi_env__ { void DrainFinalizers(); - CFRunLoopRef runtimeLoop_ = nullptr; + uint64_t threadId_ = 0; std::weak_ptr eventLoop_; bool tearingDown_ = false; v8::Eternal privateKeys_[2]; diff --git a/NativeScript/napi/NapiEnv.mm b/NativeScript/napi/NapiEnv.mm index d04a6596a..29890fdd4 100644 --- a/NativeScript/napi/NapiEnv.mm +++ b/NativeScript/napi/NapiEnv.mm @@ -15,7 +15,7 @@ NapiEnv::NapiEnv(Local context) : napi_env__(context, NODE_API_DEFAULT_MODULE_API_VERSION), - runtimeLoop_(CFRunLoopGetCurrent()), + threadId_(CurrentThreadId()), eventLoop_(Runtime::GetCurrentRuntime()->GetEventLoop()) {} NapiEnv::~NapiEnv() = default; diff --git a/NativeScript/napi/NapiThreadSafeFunction.mm b/NativeScript/napi/NapiThreadSafeFunction.mm index 6e6e25329..6482c8001 100644 --- a/NativeScript/napi/NapiThreadSafeFunction.mm +++ b/NativeScript/napi/NapiThreadSafeFunction.mm @@ -32,22 +32,14 @@ struct napi_threadsafe_function__ : public std::enable_shared_from_this { - ~napi_threadsafe_function__() { - if (loop != nullptr) { - CFRelease(loop); - } - } - // Read from producer threads, so they are fixed at construction and only - // cleared once the function is closed for good. The runloop is retained for - // the object's lifetime and used for thread-identity checks only: a producer - // may compare against it after the owning thread exits, and comparing a - // deallocated pointer is fine where calling into it would not be. Work is - // posted through the event loop, whose weak_ptr goes null once the runtime - // shuts it down. + // cleared once the function is closed for good. envThreadId is for + // thread-identity checks only (see NapiEnv::ThreadId); work is posted + // through the event loop, whose weak_ptr goes null once the runtime shuts + // it down. tns::NapiEnv* env = nullptr; v8::Isolate* isolate = nullptr; - CFRunLoopRef loop = nullptr; + uint64_t envThreadId = 0; std::weak_ptr eventLoop; // Touched on the env's thread only, which is where the abort path and every @@ -344,14 +336,10 @@ void NapiAbortThreadSafeFunctions(NapiEnv* env) { } tns::NapiEnv* tnsEnv = static_cast(env); - RETURN_STATUS_IF_FALSE(env, tnsEnv->RuntimeLoop() != nullptr, - napi_generic_failure); - TsfnRef tsfn = std::make_shared(); tsfn->env = tnsEnv; tsfn->isolate = env->isolate; - tsfn->loop = tnsEnv->RuntimeLoop(); - CFRetain(tsfn->loop); + tsfn->envThreadId = tnsEnv->ThreadId(); tsfn->eventLoop = tnsEnv->GetEventLoop(); tsfn->callJs = call_js_cb; tsfn->finalizeCb = thread_finalize_cb; @@ -407,7 +395,7 @@ napi_status NAPI_CDECL napi_get_threadsafe_function_context( // this wait, so blocking on it there can only stall forever. Node blocks // regardless and leaves this status unused; wedging the runloop is worse // than a status an addon may not expect. - if (CFRunLoopGetCurrent() == func->loop) { + if (tns::NapiEnv::CurrentThreadId() == func->envThreadId) { return napi_would_deadlock; } func->spaceAvailable.wait(lock); diff --git a/NativeScript/napi/NodeApiEmbed.mm b/NativeScript/napi/NodeApiEmbed.mm index 4609c2ae4..40a56701a 100644 --- a/NativeScript/napi/NodeApiEmbed.mm +++ b/NativeScript/napi/NodeApiEmbed.mm @@ -448,10 +448,8 @@ napi_status NAPI_CDECL napi_make_callback(napi_env env, // Entering the isolate is only ever legal from the thread that owns it; // reaching JS from anywhere else is what threadsafe functions are for. - RETURN_STATUS_IF_FALSE( - env, - CFRunLoopGetCurrent() == static_cast(env)->RuntimeLoop(), - napi_generic_failure); + RETURN_STATUS_IF_FALSE(env, static_cast(env)->IsOnEnvThread(), + napi_generic_failure); (void)async_context; @@ -559,9 +557,6 @@ void CompleteAsyncWork(napi_async_work work, napi_status status) { (void)async_resource; tns::NapiEnv* tnsEnv = static_cast(env); - RETURN_STATUS_IF_FALSE(env, tnsEnv->RuntimeLoop() != nullptr, - napi_generic_failure); - napi_async_work__* work = new napi_async_work__(); work->env = tnsEnv; work->isolate = env->isolate; diff --git a/NativeScript/runtime/ClassBuilder.mm b/NativeScript/runtime/ClassBuilder.mm index 91c066b0b..d4c18f246 100644 --- a/NativeScript/runtime/ClassBuilder.mm +++ b/NativeScript/runtime/ClassBuilder.mm @@ -380,7 +380,6 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { } if ([self retainCount] == 1) { auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); void* weakSelf = (__bridge void*)self; auto gcProtect = [isolateWrapper, weakSelf, isolate]() { auto innerCache = isolateWrapper.GetCache(); @@ -403,7 +402,7 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { }; // After the retain: reconciling reads the new retain count. id result = retain(self, @selector(retain)); - if (CFRunLoopGetCurrent() != runtimeLoop) { + if (!runtime->IsOnRuntimeThread()) { // bare entry: the closure does its own Locker ceremony, exactly // like the performed block it replaces runtime->GetEventLoop()->PostInternalBare(gcProtect); @@ -449,11 +448,10 @@ void ThrowTypeError(Isolate* isolate, const std::string& message) { } }; auto runtime = Runtime::GetRuntime(isolate); - auto runtimeLoop = runtime->RuntimeLoop(); // After the release: reconciling reads the new retain count, and // the Instances entry still holds the object. release(self, @selector(release)); - if (CFRunLoopGetCurrent() != runtimeLoop) { + if (!runtime->IsOnRuntimeThread()) { // bare entry: the closure does its own Locker ceremony, exactly // like the performed block it replaces runtime->GetEventLoop()->PostInternalBare(gcUnprotect); diff --git a/NativeScript/runtime/PromiseProxy.cpp b/NativeScript/runtime/PromiseProxy.cpp index e8ff25469..b78d4d2e2 100644 --- a/NativeScript/runtime/PromiseProxy.cpp +++ b/NativeScript/runtime/PromiseProxy.cpp @@ -1,6 +1,8 @@ #include "PromiseProxy.h" #include "BuiltinLoader.h" +#include "Caches.h" +#include "EventLoop.h" #include "Helpers.h" #include "Runtime.h" @@ -8,37 +10,72 @@ using namespace v8; namespace tns { -// Reports whether the calling thread is the isolate's runtime thread. That -// thread's run loop is where timers fire and is always being pumped, so a -// promise resolution is marshaled back to its creating thread only when that -// thread is the runtime thread; a promise created elsewhere settles on -// whichever thread resolves it. Don't use CFRunLoopGetCurrent() here: it -// creates a run loop for any thread that lacks one. -static void IsRuntimeThreadCallback(const FunctionCallbackInfo& args) { +namespace { + +struct PromiseProxyState { + // promise-proxy.js's module.exports: runs the oldest queued settlement. + Global runNext; +}; + +void RunNextSettlement(Isolate* isolate) { + PromiseProxyState* state = Caches::StateFor(isolate); + if (state == nullptr || state->runNext.IsEmpty()) { + return; + } + Local context = isolate->GetCurrentContext(); + if (context.IsEmpty()) { + return; + } + (void)state->runNext.Get(isolate)->Call(context, v8::Undefined(isolate), 0, nullptr); +} + +// Whether the calling thread is the isolate's runtime thread. Its run loop is +// always being pumped, so a promise resolution is marshaled back to its +// creating thread only when that thread is the runtime thread; a promise +// created elsewhere settles on whichever thread resolves it. +void IsRuntimeThreadCallback(const FunctionCallbackInfo& args) { Runtime* runtime = Runtime::GetRuntime(args.GetIsolate()); args.GetReturnValue().Set(runtime != nullptr && runtime->IsOnRuntimeThread()); } -void PromiseProxy::Init(v8::Local context) { - Isolate* isolate = v8::Isolate::GetCurrent(); +// Called from a foreign thread holding the isolate's Locker. Each successful +// post runs runNext exactly once on the runtime thread; false means the +// runtime is shutting down and the settlement can never run. +void PostToRuntimeThreadCallback(const FunctionCallbackInfo& args) { + Isolate* isolate = args.GetIsolate(); + Runtime* runtime = Runtime::GetRuntime(isolate); + std::shared_ptr loop = runtime != nullptr ? runtime->GetEventLoop() : nullptr; + bool posted = + loop != nullptr && loop->PostInternal([isolate]() { RunNextSettlement(isolate); }); + args.GetReturnValue().Set(posted); +} - Local isRuntimeThread; - bool success = v8::Function::New(context, IsRuntimeThreadCallback) - .ToLocal(&isRuntimeThread); +void SetFunction(Isolate* isolate, Local context, Local binding, + const char* name, FunctionCallback callback) { + Local fn; + bool success = v8::Function::New(context, callback).ToLocal(&fn) && + binding->Set(context, tns::ToV8String(isolate, name), fn).FromMaybe(false); tns::Assert(success, isolate); +} + +} // namespace + +void PromiseProxy::Init(v8::Local context) { + Isolate* isolate = v8::Isolate::GetCurrent(); Local binding = Object::New(isolate); - success = binding - ->Set(context, tns::ToV8String(isolate, "isRuntimeThread"), - isRuntimeThread) - .FromMaybe(false); - tns::Assert(success, isolate); + SetFunction(isolate, context, binding, "isRuntimeThread", IsRuntimeThreadCallback); + SetFunction(isolate, context, binding, "postToRuntimeThread", PostToRuntimeThreadCallback); - Local result; - success = - BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding) - .ToLocal(&result); + Local runNext; + bool success = + BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding).ToLocal(&runNext) && + runNext->IsFunction(); tns::Assert(success, isolate); + + PromiseProxyState* state = Caches::StateFor(isolate); + tns::Assert(state != nullptr, isolate); + state->runNext.Reset(isolate, runNext.As()); } } // namespace tns diff --git a/NativeScript/runtime/Runtime.h b/NativeScript/runtime/Runtime.h index 714e44ae6..cb2fe7dc2 100644 --- a/NativeScript/runtime/Runtime.h +++ b/NativeScript/runtime/Runtime.h @@ -50,8 +50,6 @@ class Runtime { inline bool IsRuntimeWorker() { return workerId_ > 0; } - inline CFRunLoopRef RuntimeLoop() { return runtimeLoop_; } - inline bool IsOnRuntimeThread() const { return pthread_equal(runtimeThread_, pthread_self()) != 0; } /* diff --git a/NativeScript/runtime/Runtime.mm b/NativeScript/runtime/Runtime.mm index e60a35abb..1dd423f0f 100644 --- a/NativeScript/runtime/Runtime.mm +++ b/NativeScript/runtime/Runtime.mm @@ -854,12 +854,12 @@ bool OnRuntimeThreadOf(v8::Isolate* isolate) { SpinLock lock(isolatesMutex_); for (Isolate* isolate : Runtime::isolates_) { Runtime* candidate = GetRuntime(isolate); - // The home-loop comparison closes the allocator-reuse (ABA) hole: a stale - // thread-local can only exist on the dead runtime's home thread, and a - // recycled same-address Runtime homed on this thread would have + // The home-thread comparison closes the allocator-reuse (ABA) hole: a + // stale thread-local can only exist on the dead runtime's home thread, and + // a recycled same-address Runtime homed on this thread would have // overwritten that thread-local — so an address match with a foreign home - // loop can only be a recycled pointer. - if (candidate == runtime && candidate->RuntimeLoop() == CFRunLoopGetCurrent()) { + // thread can only be a recycled pointer. + if (candidate == runtime && candidate->IsOnRuntimeThread()) { return candidate->GetNapiEnv(); } } diff --git a/NativeScript/runtime/js/promise-proxy.js b/NativeScript/runtime/js/promise-proxy.js index b831ea944..719a147ac 100644 --- a/NativeScript/runtime/js/promise-proxy.js +++ b/NativeScript/runtime/js/promise-proxy.js @@ -2,23 +2,44 @@ // that thread is the runtime thread. A Promise created on a background // thread settles on whichever thread resolves it, because the background // run loop may be dormant and marshaling a resolution to it would hang. -// -// Never call CFRunLoopGetCurrent() off the runtime thread: it creates a run -// loop for any thread that lacks one. -const { isRuntimeThread } = binding; +const { isRuntimeThread, postToRuntimeThread } = binding; const { FunctionPrototypeBind, Proxy } = primordials; -// The runtime loop never changes for an isolate, so it is fetched once, on -// the runtime thread, the first time a Promise is created there. -let runtimeLoop; +// Settlements waiting for the runtime thread, oldest first. Every successful +// postToRuntimeThread() makes the runtime thread call runNext() exactly once, +// so queued nodes and posts pair 1:1. +let head = null; +let tail = null; + +function enqueue(settle) { + if (!postToRuntimeThread()) { + return; + } + const node = { settle, next: null }; + if (tail === null) { + head = node; + } else { + tail.next = node; + } + tail = node; +} + +function runNext() { + const node = head; + if (node === null) { + return; + } + head = node.next; + if (head === null) { + tail = null; + } + node.settle(); +} global.Promise = new Proxy(global.Promise, { construct: function(target, args) { let origFunc = args[0]; const originIsRuntimeThread = isRuntimeThread(); - if (originIsRuntimeThread && runtimeLoop === undefined) { - runtimeLoop = CFRunLoopGetCurrent(); - } let promise = new target(function(resolve, reject) { function isFulfilled() { @@ -34,26 +55,22 @@ global.Promise = new Proxy(global.Promise, { return; } const resolveCall = FunctionPrototypeBind(resolve, this, value); + markFulfilled(); if (!originIsRuntimeThread || isRuntimeThread()) { - markFulfilled(); resolveCall(); } else { - CFRunLoopPerformBlock(runtimeLoop, kCFRunLoopDefaultMode, resolveCall); - CFRunLoopWakeUp(runtimeLoop); - markFulfilled(); + enqueue(resolveCall); } }, reason => { if (isFulfilled()) { return; } const rejectCall = FunctionPrototypeBind(reject, this, reason); + markFulfilled(); if (!originIsRuntimeThread || isRuntimeThread()) { - markFulfilled(); rejectCall(); } else { - CFRunLoopPerformBlock(runtimeLoop, kCFRunLoopDefaultMode, rejectCall); - CFRunLoopWakeUp(runtimeLoop); - markFulfilled(); + enqueue(rejectCall); } }); }); @@ -64,3 +81,5 @@ global.Promise = new Proxy(global.Promise, { return promise; } }); + +module.exports = runNext; diff --git a/TestRunner/app/tests/Promises.js b/TestRunner/app/tests/Promises.js index 8a01ff90f..99693895d 100644 --- a/TestRunner/app/tests/Promises.js +++ b/TestRunner/app/tests/Promises.js @@ -133,6 +133,37 @@ describe("Promise scheduling", function () { }); }); + it("settles promises resolved back-to-back on a background thread in resolution order", done => { + const expectedHash = NSThread.currentThread.hash; + const count = 5; + const resolvers = []; + const order = []; + const settled = []; + for (let i = 0; i < count; i++) { + settled.push(new Promise((resolve, reject) => { + resolvers.push(i % 2 === 0 ? () => resolve(i) : () => reject(i)); + }).then(value => { + expect(NSThread.currentThread.hash).toBe(expectedHash); + order.push(value); + }, reason => { + expect(NSThread.currentThread.hash).toBe(expectedHash); + order.push(reason); + })); + } + + const queue = NSOperationQueue.alloc().init(); + queue.addOperationWithBlock(() => { + for (let i = count - 1; i >= 0; i--) { + resolvers[i](); + } + }); + + Promise.all(settled).then(() => { + expect(order).toEqual([4, 3, 2, 1, 0]); + done(); + }); + }); + it("the 'then' callback runs for a Promise created on a background thread and resolved on the runtime loop", done => { // https://github.com/NativeScript/ios/issues/330 // The promise is constructed on a background dispatch queue whose run From 486ac42a00a49d5e13be44a38fde8ac17e4c3776 Mon Sep 17 00:00:00 2001 From: Eduardo Speroni Date: Thu, 26 Nov 2026 17:41:10 -0300 Subject: [PATCH 3/3] refactor(runtime): Promise proxy init uses NS_CHECK instead of tns::Assert --- NativeScript/runtime/PromiseProxy.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/NativeScript/runtime/PromiseProxy.cpp b/NativeScript/runtime/PromiseProxy.cpp index b78d4d2e2..60ecad820 100644 --- a/NativeScript/runtime/PromiseProxy.cpp +++ b/NativeScript/runtime/PromiseProxy.cpp @@ -2,6 +2,7 @@ #include "BuiltinLoader.h" #include "Caches.h" +#include "Checks.h" #include "EventLoop.h" #include "Helpers.h" #include "Runtime.h" @@ -55,7 +56,7 @@ void SetFunction(Isolate* isolate, Local context, Local binding Local fn; bool success = v8::Function::New(context, callback).ToLocal(&fn) && binding->Set(context, tns::ToV8String(isolate, name), fn).FromMaybe(false); - tns::Assert(success, isolate); + NS_CHECK(success, std::string("cannot install the Promise proxy binding ") + name); } } // namespace @@ -68,13 +69,12 @@ void PromiseProxy::Init(v8::Local context) { SetFunction(isolate, context, binding, "postToRuntimeThread", PostToRuntimeThreadCallback); Local runNext; - bool success = - BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding).ToLocal(&runNext) && - runNext->IsFunction(); - tns::Assert(success, isolate); + NS_CHECK(BuiltinLoader::RunBuiltin(context, BuiltinId::kPromiseProxy, binding).ToLocal(&runNext), + "the promise-proxy builtin threw"); + NS_CHECK(runNext->IsFunction(), "the promise-proxy builtin must export a function"); PromiseProxyState* state = Caches::StateFor(isolate); - tns::Assert(state != nullptr, isolate); + NS_CHECK(state != nullptr, "Promise proxy initialized on an isolate that is tearing down"); state->runNext.Reset(isolate, runNext.As()); }