From e10f9224ac0e388ea15b8ec91aef45613ee76319 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Mon, 11 Nov 2019 00:02:11 +0200 Subject: [PATCH] doc: add mention for using promisify on class methods Fixes: https://github.com/nodejs/node/issues/30344 PR-URL: https://github.com/nodejs/node/pull/30355 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater --- doc/api/util.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/doc/api/util.md b/doc/api/util.md index 6435709bd84331..3a9ca53e177533 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -859,6 +859,34 @@ will throw an error. If `original` is a function but its last argument is not an error-first callback, it will still be passed an error-first callback as its last argument. +Using `promisify()` on class methods or other methods that use `this` may not +work as expected unless handled specially: + +```js +const util = require('util'); + +class Foo { + constructor() { + this.a = 42; + } + + bar(callback) { + callback(null, this.a); + } +} + +const foo = new Foo(); + +const naiveBar = util.promisify(foo.bar); +// TypeError: Cannot read property 'a' of undefined +// naiveBar().then(a => console.log(a)); + +naiveBar.call(foo).then((a) => console.log(a)); // '42' + +const bindBar = naiveBar.bind(foo); +bindBar().then((a) => console.log(a)); // '42' +``` + ### Custom promisified functions Using the `util.promisify.custom` symbol one can override the return value of