CodePark/ problems / promisify
START PRACTICINGPRACTICE
Coding problem · JavaScript utilities › Promise combinators

promisify

easyabout 12 minutes in an interview

Implement promisify(fn). fn uses the Node.js callback style. Its last parameter is a callback (err, value) => void.

Return a new function that takes the same arguments without the callback. The new function returns a promise.

  • Call fn with the given arguments plus your own callback. Call it with the same this.
  • If err is truthy, reject with err. Otherwise resolve with value, even when value is falsy, such as 0 or ''.
  • If fn throws synchronously, the promise rejects with that error. Synchronously means right away, during the call, instead of through the callback.
  • Don't use util.promisify.
Input: const read = promisify((name, cb) => cb(null, 'hi ' + name)); await read('Ada') Output: 'hi Ada'
Input: const fail = promisify(cb => cb(new Error('nope'))); await fail() Output: rejects with Error('nope')