From 2fb3d5153f66b5c455a3d554b80a874ebc7d9314 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Mon, 11 Sep 2023 16:44:10 +0200 Subject: [PATCH] util: runtime deprecate `promisify`-ing a function returning a `Promise` --- lib/internal/util.js | 6 ++++-- test/parallel/test-util-promisify.js | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/internal/util.js b/lib/internal/util.js index 3586084ba7b8bd..48724374b0eec0 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -63,7 +63,7 @@ const { sleep: _sleep, toUSVString: _toUSVString, } = internalBinding('util'); -const { isNativeError } = internalBinding('types'); +const { isNativeError, isPromise } = internalBinding('types'); const { getOptionValue } = require('internal/options'); const noCrypto = !process.versions.openssl; @@ -409,7 +409,9 @@ function promisify(original) { resolve(values[0]); } }); - ReflectApply(original, this, args); + if (isPromise(ReflectApply(original, this, args))) { + process.emitWarning('Calling promisify on a function that returns a Promise is likely a mistake.'); + } }); } diff --git a/test/parallel/test-util-promisify.js b/test/parallel/test-util-promisify.js index 0fc2d650ee9272..82e7218eabcc46 100644 --- a/test/parallel/test-util-promisify.js +++ b/test/parallel/test-util-promisify.js @@ -7,6 +7,21 @@ const vm = require('vm'); const { promisify } = require('util'); const { customPromisifyArgs } = require('internal/util'); +{ + const warningHandler = common.mustNotCall(); + process.on('warning', warningHandler); + function foo() {} + foo.constructor = (async () => {}).constructor; + promisify(foo); + process.off('warning', warningHandler); +} + +common.expectWarning('Warning', 'Calling promisify on a function that returns a Promise is likely a mistake.'); +promisify(async (callback) => { callback(); })().then(common.mustCall(() => { + common.expectWarning('Warning', 'Calling promisify on a function that returns a Promise is likely a mistake.'); + promisify(async () => {})().then(common.mustNotCall()); +})); + const stat = promisify(fs.stat); {