diff --git a/src/node.cc b/src/node.cc index c1d0e62009dc10..fa8b44e64d0cfd 100644 --- a/src/node.cc +++ b/src/node.cc @@ -4672,6 +4672,15 @@ void RunAtExit(Environment* env) { } +uv_loop_t* GetCurrentEventLoop(v8::Isolate* isolate) { + HandleScope handle_scope(isolate); + auto context = isolate->GetCurrentContext(); + if (context.IsEmpty()) + return nullptr; + return Environment::GetCurrent(context)->event_loop(); +} + + static uv_key_t thread_local_env; diff --git a/src/node.h b/src/node.h index 43792473453ec8..76cab566eab258 100644 --- a/src/node.h +++ b/src/node.h @@ -227,6 +227,10 @@ NODE_EXTERN void EmitBeforeExit(Environment* env); NODE_EXTERN int EmitExit(Environment* env); NODE_EXTERN void RunAtExit(Environment* env); +// This may return nullptr if the current v8::Context is not associated +// with a Node instance. +NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate); + /* Converts a unixtime to V8 Date */ #define NODE_UNIXTIME_V8(t) v8::Date::New(v8::Isolate::GetCurrent(), \ 1000 * static_cast(t)) diff --git a/test/addons/async-hello-world/binding.cc b/test/addons/async-hello-world/binding.cc index f773bfffcdb95d..5b3a800709f7d7 100644 --- a/test/addons/async-hello-world/binding.cc +++ b/test/addons/async-hello-world/binding.cc @@ -77,7 +77,7 @@ void Method(const v8::FunctionCallbackInfo& args) { v8::Local callback = v8::Local::Cast(args[1]); req->callback.Reset(isolate, callback); - uv_queue_work(uv_default_loop(), + uv_queue_work(node::GetCurrentEventLoop(isolate), &req->req, DoAsync, (uv_after_work_cb)AfterAsync); diff --git a/test/addons/callback-scope/binding.cc b/test/addons/callback-scope/binding.cc index f03d8a20d5333f..34d452bbb7c710 100644 --- a/test/addons/callback-scope/binding.cc +++ b/test/addons/callback-scope/binding.cc @@ -52,7 +52,10 @@ static void TestResolveAsync(const v8::FunctionCallbackInfo& args) { uv_work_t* req = new uv_work_t; - uv_queue_work(uv_default_loop(), req, [](uv_work_t*) {}, Callback); + uv_queue_work(node::GetCurrentEventLoop(isolate), + req, + [](uv_work_t*) {}, + Callback); } v8::Local local =