Skip to content
Onsite

Promisify

MediumP2Coding

Implement promisify(fn), which converts a Node-style callback function into one that returns a promise.

fn takes its normal arguments followed by a callback (err, result) => void as its last argument. promisify(fn) returns a function that accepts only the normal arguments, calls fn with them plus its own callback, and returns a promise that:

  • rejects with err if the callback receives a truthy first argument,
  • otherwise resolves with result (undefined if none is passed).

The returned function must pass this through to fn. If fn throws synchronously, the promise rejects with that error.

Example 1

Input
const read = promisify((path, cb) => cb(null, 'data:' + path)); await read('a.txt');
Output
'data:a.txt'

Constraints

  • fn always receives the callback as its final argument.

Hints

Run checks the 3 visible tests, Submit all 8.