diff --git a/src/api/callback.cc b/src/api/callback.cc index 3d4f91a866ea39..8a0b71cd3626e2 100644 --- a/src/api/callback.cc +++ b/src/api/callback.cc @@ -266,6 +266,34 @@ MaybeLocal MakeCallback(Isolate* isolate, return ret; } +// Use this if you just want to safely invoke some JS callback and +// would like to retain the currently active async_context, if any. +// In case none is available, a fixed default context will be +// installed otherwise. +MaybeLocal MakeSyncCallback(Isolate* isolate, + Local recv, + Local callback, + int argc, + Local argv[]) { + Environment* env = Environment::GetCurrent(callback->CreationContext()); + CHECK_NOT_NULL(env); + if (!env->can_call_into_js()) return Local(); + + Context::Scope context_scope(env->context()); + if (env->async_callback_scope_depth()) { + // There's another MakeCallback() on the stack, piggy back on it. + // In particular, retain the current async_context. + return callback->Call(env->context(), recv, argc, argv); + } + + // This is a toplevel invocation and the caller (intentionally) + // didn't provide any async_context to run in. Install a default context. + MaybeLocal ret = + InternalMakeCallback(env, env->process_object(), recv, callback, argc, argv, + async_context{0, 0}); + return ret; +} + // Legacy MakeCallback()s Local MakeCallback(Isolate* isolate, diff --git a/src/node_internals.h b/src/node_internals.h index f7a1e2d8d62c24..b75092d662dc97 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -200,6 +200,12 @@ v8::MaybeLocal InternalMakeCallback( v8::Local argv[], async_context asyncContext); +v8::MaybeLocal MakeSyncCallback(v8::Isolate* isolate, + v8::Local recv, + v8::Local callback, + int argc, + v8::Local argv[]); + class InternalCallbackScope { public: enum Flags {