4 ms·
Promisify is a super simple function to write yourself though. const promisify = (fn, ctx) => (...args) => new Promise((resolve, reject) => fn.appl
by idbehold 9y ago
Promisify is a super simple function to write yourself though.
const promisify = (fn, ctx) => (...args) =>
new Promise((resolve, reject) =>
fn.apply(ctx, [ ...args,
(err, data) => err ? reject(err) : resolve(data)
])
)
- elmigranto 9y agoAlmost. Don't forget about the case where callback receives multiple arguments, and the fact that someone might decide to change the API for callback signature like `(err, result)` to `(err, result, stats)`, for example.
- idbehold 9y agoPromises only support a single success value so if you're "promisifying" something then you're only going to the second argument as the resolved value. The new util.promisify() doesn't provide said functionality [1] will only resolve the second argument [2] unless you define a custom function on the original function. [1]: https://nodejs.org/api/util.html#util_util_promisify_original https://nodejs.org/api/util.html#util_util_promisify_origina... [2]: https://github.com/nodejs/node/blob/ef16319effe396622666268cd8100ad8d586c4ee/lib/internal/util.js#L204-L245 https://github.com/nodejs/node/blob/ef16319effe396622666268c...
- elmigranto 9y agoA bunch of functions in core return multiple things to callback. A lot more in userland do the same. Spec or not, that is still something that needs to be accounted for.
- idbehold 9y agoThose are handled by `util.promisify()` by having the original function define special properties on itself `Symbol('util.promisify.custom')` and `Symbol('customPromisifyArgs')`. But it's not something handled by default (e.g. resolving an array if the callback gets more than 2 arguments passed to it).
- bfred_it 9y agoBut why. If you're gonna take special steps to handle `util.promisify` you might as well just offer a Promised API and skip `util.promisify`
- rattray 9y agoThe problem is that everyone does that slightly differently. Having a stdlib function makes for an easy "let's just use this everywhere" answer.