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
errif the callback receives a truthy first argument, - otherwise resolves with
result(undefinedif 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.