Skip to content

Commit 7ef2f2a

Browse files
committed
lib: created isValidCallback helper
check for callback function is moved to a separate function. This piece of code is being shared by other entities as well.
1 parent c452632 commit 7ef2f2a

File tree

2 files changed

+12
-11
lines changed

2 files changed

+12
-11
lines changed

lib/internal/validators.js

+8-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ const {
1414
ERR_INVALID_ARG_TYPE,
1515
ERR_INVALID_ARG_VALUE,
1616
ERR_OUT_OF_RANGE,
17-
ERR_UNKNOWN_SIGNAL
17+
ERR_UNKNOWN_SIGNAL,
18+
ERR_INVALID_CALLBACK,
1819
}
1920
} = require('internal/errors');
2021
const { normalizeEncoding } = require('internal/util');
@@ -194,6 +195,11 @@ function validatePort(port, name = 'Port', { allowZero = true } = {}) {
194195
return port | 0;
195196
}
196197

198+
const validateCallback = hideStackFrames((callback) => {
199+
if (typeof callback !== 'function')
200+
throw new ERR_INVALID_CALLBACK(callback);
201+
});
202+
197203
module.exports = {
198204
isInt32,
199205
isUint32,
@@ -210,4 +216,5 @@ module.exports = {
210216
validateSignalName,
211217
validateString,
212218
validateUint32,
219+
validateCallback,
213220
};

lib/timers.js

+4-10
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ const {
5353
promisify: { custom: customPromisify },
5454
deprecate
5555
} = require('internal/util');
56-
const { ERR_INVALID_CALLBACK } = require('internal/errors').codes;
5756
const debug = require('internal/util/debuglog').debuglog('timer');
57+
const { validateCallback } = require('internal/validators');
5858

5959
const {
6060
destroyHooksExist,
@@ -118,9 +118,7 @@ function enroll(item, msecs) {
118118

119119

120120
function setTimeout(callback, after, arg1, arg2, arg3) {
121-
if (typeof callback !== 'function') {
122-
throw new ERR_INVALID_CALLBACK(callback);
123-
}
121+
validateCallback(callback);
124122

125123
let i, args;
126124
switch (arguments.length) {
@@ -165,9 +163,7 @@ function clearTimeout(timer) {
165163
}
166164

167165
function setInterval(callback, repeat, arg1, arg2, arg3) {
168-
if (typeof callback !== 'function') {
169-
throw new ERR_INVALID_CALLBACK(callback);
170-
}
166+
validateCallback(callback);
171167

172168
let i, args;
173169
switch (arguments.length) {
@@ -249,9 +245,7 @@ const Immediate = class Immediate {
249245
};
250246

251247
function setImmediate(callback, arg1, arg2, arg3) {
252-
if (typeof callback !== 'function') {
253-
throw new ERR_INVALID_CALLBACK(callback);
254-
}
248+
validateCallback(callback);
255249

256250
let i, args;
257251
switch (arguments.length) {

0 commit comments

Comments
 (0)