Skip to content

Commit 43acce1

Browse files
elyalvaradotargos
authored andcommitted
worker: handle calling terminate when kHandler is null
This PR makes a change to the Worker.terminate() when called if the kHandler is null. Before this pull request it was returning undefined, but the API is expecting a promise. With the changes in this PR if terminate is called a Promise.resolve() is returned, unless a callback is passed in which case the old behavior stays (returns undefined). PR-URL: #28370 Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Tiancheng "Timothy" Gu <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Rich Trott <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 464136f commit 43acce1

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

lib/internal/worker.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,18 +224,19 @@ class Worker extends EventEmitter {
224224
}
225225

226226
terminate(callback) {
227-
if (this[kHandle] === null) return;
228-
229227
debug(`[${threadId}] terminates Worker with ID ${this.threadId}`);
230228

231229
if (typeof callback === 'function') {
232230
process.emitWarning(
233231
'Passing a callback to worker.terminate() is deprecated. ' +
234232
'It returns a Promise instead.',
235233
'DeprecationWarning', 'DEP0132');
234+
if (this[kHandle] === null) return Promise.resolve();
236235
this.once('exit', (exitCode) => callback(null, exitCode));
237236
}
238237

238+
if (this[kHandle] === null) return Promise.resolve();
239+
239240
this[kHandle].stopThread();
240241

241242
// Do not use events.once() here, because the 'exit' event will always be
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const { Worker } = require('worker_threads');
5+
6+
// Test that calling worker.terminate() if kHandler is null should return an
7+
// empty promise that resolves to undefined, even when a callback is passed
8+
9+
const worker = new Worker(`
10+
const { parentPort } = require('worker_threads');
11+
parentPort.postMessage({ hello: 'world' });
12+
`, { eval: true });
13+
14+
process.once('beforeExit', common.mustCall(() => {
15+
console.log('beforeExit');
16+
worker.ref();
17+
}));
18+
19+
worker.on('exit', common.mustCall(() => {
20+
console.log('exit');
21+
worker.terminate().then((res) => assert.strictEqual(res, undefined));
22+
worker.terminate(() => null).then(
23+
(res) => assert.strictEqual(res, undefined)
24+
);
25+
}));
26+
27+
worker.unref();

0 commit comments

Comments
 (0)