Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: add mention for using promisify on class methods #30355

Closed
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
BridgeAR marked this conversation as resolved.
Show resolved Hide resolved
or other methods that use `this` from the context may not work as expected
Trott marked this conversation as resolved.
Show resolved Hide resolved
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