Skip to content

Commit 51a92b9

Browse files
lundibunditargos
authored andcommitted
doc: add mention for using promisify on class methods
Fixes: #30344 PR-URL: #30355 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]>
1 parent 89f28cc commit 51a92b9

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/api/util.md

+28
Original file line numberDiff line numberDiff line change
@@ -859,6 +859,34 @@ will throw an error. If `original` is a function but its last argument is not
859859
an error-first callback, it will still be passed an error-first
860860
callback as its last argument.
861861

862+
Using `promisify()` on class methods or other methods that use `this` may not
863+
work as expected unless handled specially:
864+
865+
```js
866+
const util = require('util');
867+
868+
class Foo {
869+
constructor() {
870+
this.a = 42;
871+
}
872+
873+
bar(callback) {
874+
callback(null, this.a);
875+
}
876+
}
877+
878+
const foo = new Foo();
879+
880+
const naiveBar = util.promisify(foo.bar);
881+
// TypeError: Cannot read property 'a' of undefined
882+
// naiveBar().then(a => console.log(a));
883+
884+
naiveBar.call(foo).then((a) => console.log(a)); // '42'
885+
886+
const bindBar = naiveBar.bind(foo);
887+
bindBar().then((a) => console.log(a)); // '42'
888+
```
889+
862890
### Custom promisified functions
863891

864892
Using the `util.promisify.custom` symbol one can override the return value of

0 commit comments

Comments
 (0)