Skip to content

Commit 8138e9c

Browse files
lundibunditrivikr
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 c8d00d9 commit 8138e9c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/api/util.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,34 @@ will throw an error. If `original` is a function but its last argument is not
862862
an error-first callback, it will still be passed an error-first
863863
callback as its last argument.
864864

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

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

0 commit comments

Comments
 (0)