Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions doc/api/deprecations.md
Original file line number Diff line number Diff line change
Expand Up @@ -3921,6 +3921,9 @@ The `assert.CallTracker` API has been removed.

<!-- YAML
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/67489
description: Deprecation revoked.
- version: v21.0.0
pr-url: https://github.com/nodejs/node/pull/49609
description: Runtime deprecation.
Expand All @@ -3929,10 +3932,14 @@ changes:
description: Documentation-only deprecation.
-->

Type: Runtime
Type: Deprecation revoked

Calling [`util.promisify`][] on a function that returns a `Promise` will ignore
the result of said promise, which can lead to unhandled promise rejections.
Calling [`util.promisify`][] on a function that returns a `Promise` used to
ignore the result of said promise, which could lead to unhandled promise
rejections. The deprecation was revoked because this is a likely mistake rather
than use of a deprecated API. Rejections of the returned `Promise` are now
forwarded to the promise returned by the promisified function, and a regular
process warning with the code `PROMISIFY_RETURNED_PROMISE` is emitted instead.

### DEP0175: `util.toUSVString`

Expand Down
18 changes: 18 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -2567,6 +2567,12 @@ parseEnv('HELLO=world\nHELLO=oh my\n');
<!-- YAML
added: v8.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/67489
description: Calling `promisify` on a function that returns a `Promise` no
longer emits a deprecation warning. Rejections of the returned
`Promise` are forwarded, and a `PROMISIFY_RETURNED_PROMISE`
warning is emitted instead.
- version: v20.8.0
pr-url: https://github.com/nodejs/node/pull/49647
description: Calling `promisify` on a function that returns a `Promise` is
Expand Down Expand Up @@ -2637,6 +2643,17 @@ callStat();
If there is an `original[util.promisify.custom]` property present, `promisify`
will return its value, see [Custom promisified functions][].

`promisify()` is intended for functions that report their result through a
callback. If `original` returns a `Promise`, a warning with the code
`PROMISIFY_RETURNED_PROMISE` is emitted the first time the promisified function
is called. The promisified function still settles when the callback is called,
but if the returned `Promise` rejects first, the promisified function rejects
with the same reason. If `original` returns a `Promise` and never calls the
callback, the promise returned by the promisified function never settles; call
such functions directly instead of using `promisify()`.
The warning can be silenced with
[`--disable-warning=PROMISIFY_RETURNED_PROMISE`][`--disable-warning`].

`promisify()` assumes that `original` is a function taking a callback as its
final argument in all cases. If `original` is not a function, `promisify()`
will throw an error. If `original` is a function but its last argument is not
Expand Down Expand Up @@ -4166,6 +4183,7 @@ npx codemod@latest @nodejs/util-is
[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
[`'uncaughtException'`]: process.md#event-uncaughtexception
[`'warning'`]: process.md#event-warning
[`--disable-warning`]: cli.md#--disable-warningcode-or-type
[`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
[`ArrayBuffer.isView()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView
[`Error.isError`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError
Expand Down
24 changes: 21 additions & 3 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const {
ObjectSetPrototypeOf,
ObjectValues,
Promise,
PromisePrototypeThen,
ReflectApply,
ReflectConstruct,
RegExpPrototypeExec,
Expand Down Expand Up @@ -474,9 +475,13 @@ function promisify(original) {
// arguments, e.g. ['bytesRead', 'buffer'] for fs.read.
const argumentNames = original[kCustomPromisifyArgsSymbol];

let warnedReturnedPromise = false;

function fn(...args) {
return new Promise((resolve, reject) => {
let settled = false;
ArrayPrototypePush(args, (err, ...values) => {
settled = true;
if (err) {
return reject(err);
}
Expand All @@ -489,9 +494,22 @@ function promisify(original) {
resolve(values[0]);
}
});
if (isPromise(ReflectApply(original, this, args))) {
process.emitWarning('Calling promisify on a function that returns a Promise is likely a mistake.',
'DeprecationWarning', 'DEP0174');
const result = ReflectApply(original, this, args);
if (isPromise(result)) {
if (!warnedReturnedPromise) {
warnedReturnedPromise = true;
process.emitWarning(
'Calling promisify on a function that returns a Promise is likely a mistake.',
{ code: 'PROMISIFY_RETURNED_PROMISE' });
}
// Forward rejections of the returned Promise so that they are not
// left unhandled. If the callback already settled the result, rethrow
// so that the rejection is still reported rather than silently lost.
PromisePrototypeThen(result, undefined, (err) => {
if (settled) throw err;
settled = true;
reject(err);
});
}
});
}
Expand Down
60 changes: 60 additions & 0 deletions test/parallel/test-util-promisify-returned-promise.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
'use strict';
// Flags: --no-deprecation
const common = require('../common');
const assert = require('assert');
const { promisify } = require('util');

// Calling a promisified function that returns a Promise emits a regular
// warning, once per promisified function. It is not a deprecation warning, so
// --no-deprecation does not affect it; it can be silenced with
// --disable-warning=PROMISIFY_RETURNED_PROMISE.
process.on('warning', common.mustCall((warning) => {
assert.strictEqual(warning.name, 'Warning');
assert.strictEqual(warning.code, 'PROMISIFY_RETURNED_PROMISE');
assert.strictEqual(
warning.message,
'Calling promisify on a function that returns a Promise is likely a mistake.');
}, 5));

// The callback is still used to settle the result, and the warning is only
// emitted once even when the promisified function is called several times.
{
const fn = promisify(async (value, callback) => { callback(null, value); });
fn(1).then((value) => assert.strictEqual(value, 1)).then(common.mustCall());
fn(2).then((value) => assert.strictEqual(value, 2)).then(common.mustCall());
}

// Errors passed to the callback still reject the result.
{
const error = new Error('callback error');
assert.rejects(promisify(async (callback) => { callback(error); })(), error)
.then(common.mustCall());
}

// Rejections of the returned Promise are forwarded instead of being left
// unhandled.
{
const error = new Error('returned promise rejection');
assert.rejects(promisify(async () => { throw error; })(), error)
.then(common.mustCall());
}

// If the callback already settled the result, a later rejection of the
// returned Promise is still reported as an unhandled rejection rather than
// being silently swallowed.
{
const error = new Error('rejection after callback');
process.on('unhandledRejection', common.mustCall((reason) => {
assert.strictEqual(reason, error);
}));
promisify(async (callback) => {
callback(null, 'value');
throw error;
})().then((value) => assert.strictEqual(value, 'value')).then(common.mustCall());
}

// A returned Promise that fulfills without the callback being called does not
// settle the result.
{
promisify(async () => {})().then(common.mustNotCall('never settling promise expected'));
}
14 changes: 0 additions & 14 deletions test/parallel/test-util-promisify.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,6 @@ const { customPromisifyArgs } = require('internal/util');
process.off('warning', warningHandler);
}

common.expectWarning(
'DeprecationWarning',
'Calling promisify on a function that returns a Promise is likely a mistake.',
'DEP0174');
promisify(async (callback) => { callback(); })().then(common.mustCall(() => {
// We must add the second `expectWarning` call in the `.then` handler, when
// the first warning has already been triggered.
common.expectWarning(
'DeprecationWarning',
'Calling promisify on a function that returns a Promise is likely a mistake.',
'DEP0174');
promisify(async () => {})().then(common.mustNotCall('never settling promise expected'));
}));

const stat = promisify(fs.stat);

{
Expand Down
Loading