From 607653c0f12a99981dbf3118b60b84ded4084d50 Mon Sep 17 00:00:00 2001 From: Alexander Borisov Date: Wed, 19 Dec 2018 15:56:13 +0300 Subject: Node.js: calling write callback asynchronously. --- src/nodejs/unit-http/http_server.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src/nodejs/unit-http') diff --git a/src/nodejs/unit-http/http_server.js b/src/nodejs/unit-http/http_server.js index c93d2b10..28f2303f 100755 --- a/src/nodejs/unit-http/http_server.js +++ b/src/nodejs/unit-http/http_server.js @@ -217,7 +217,19 @@ ServerResponse.prototype._writeBody = function(chunk, encoding, callback) { } if (typeof callback === 'function') { - callback(this); + /* + * The callback must be called only when response.write() caller + * completes. process.nextTick() postpones the callback execution. + * + * process.nextTick() is not technically part of the event loop. + * Instead, the nextTickQueue will be processed after the current + * operation completes, regardless of the current phase of + * the event loop. All callbacks passed to process.nextTick() + * will be resolved before the event loop continues. + */ + process.nextTick(function () { + callback(this); + }.bind(this)); } }; -- cgit