Skip to content

Commit

Permalink
doc: add mention for using promisify on class methods
Browse files Browse the repository at this point in the history
Fixes: #30344

PR-URL: #30355
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
  • Loading branch information
lundibundi authored and MylesBorins committed Nov 21, 2019
1 parent 9940116 commit ab887bd
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,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
Expand Down

0 comments on commit ab887bd

Please sign in to comment.