diff --git a/src/tls_wrap.cc b/src/tls_wrap.cc index 71adbdfc52ca36..82f12bd6821085 100644 --- a/src/tls_wrap.cc +++ b/src/tls_wrap.cc @@ -291,14 +291,22 @@ void TLSWrap::EncOut() { NODE_COUNT_NET_BYTES_SENT(write_size_); - if (!res.async) { - HandleScope handle_scope(env()->isolate()); - - // Simulate asynchronous finishing, TLS cannot handle this at the moment. - env()->SetImmediate([](Environment* env, void* data) { - static_cast(data)->OnStreamAfterWrite(nullptr, 0); - }, this, object()); - } + if (!res.async) + SyncAfterWrite(); +} + +// Simulate asynchronous finishing, TLS cannot handle this at the moment. +void TLSWrap::SyncAfterWrite() { + env()->isolate()->EnqueueMicrotask([](void* data) { + TLSWrap* wrap = static_cast(data); + wrap->MakeWeak(wrap); + wrap->OnStreamAfterWrite(nullptr, 0); + }, this); + ClearWeak(); + // This is a cheap way for us to ensure that microtasks will get to run + // at some point in the near future. + if (env()->immediate_info()->count() == 0) + env()->SetImmediate([](Environment* env, void* data) {}, this); } diff --git a/src/tls_wrap.h b/src/tls_wrap.h index 95e0c09cd8f971..8b8104c4c6f419 100644 --- a/src/tls_wrap.h +++ b/src/tls_wrap.h @@ -164,6 +164,8 @@ class TLSWrap : public AsyncWrap, bool eof_; private: + void SyncAfterWrite(); + static void GetWriteQueueSize( const v8::FunctionCallbackInfo& info); };