From 23ce94aa93ef163267f1147eca269f50cab30886 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Mon, 11 Nov 2019 00:02:11 +0200 Subject: [PATCH 1/2] doc: add mention for using promisify on class methods Fixes: https://github.com/nodejs/node/issues/30344 --- doc/api/util.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/doc/api/util.md b/doc/api/util.md index a38288d4585867..feb78992b34046 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -862,6 +862,35 @@ 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. +Due to the way JavaScript Context works using `promisify()` on class methods +or other methods that use `this` from the context 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 From 01925ef4b5f51247ea1de4d0b3397cf5ba2f9686 Mon Sep 17 00:00:00 2001 From: Denys Otrishko Date: Mon, 11 Nov 2019 10:55:57 +0200 Subject: [PATCH 2/2] fixup! doc: add mention for using promisify on class methods --- doc/api/util.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/api/util.md b/doc/api/util.md index feb78992b34046..ac23f138ad0d17 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -862,9 +862,8 @@ 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. -Due to the way JavaScript Context works using `promisify()` on class methods -or other methods that use `this` from the context may not work as expected -unless handled specially: +Using `promisify()` on class methods or other methods that use `this` may not +work as expected unless handled specially: ```js const util = require('util');