Promisify a callback API
intermediate Callbacks Challenge 11 of 18
Write promisify(fn). fn is a Node-style function whose last parameter is a callback called as callback(err, value). promisify returns a new function that takes the same arguments (without the callback) and returns a Promise.
Requirements
- The returned function always returns a
Promise. - Resolve with
valuewhenerris null or undefined. Reject witherrotherwise. - Pass every argument through to
fn, in order, before the callback. - Preserve
this, so promisified methods still work. - Work whether
fncalls its callback synchronously or asynchronously.
Expected output
const readConfig = promisify((name, cb) => setTimeout(() => cb(null, { name }), 10)); await readConfig('qa') → { name: 'qa' }
Test cases (6)
- ○returns a promise
- ○resolves with the callback value
- ○rejects with the callback error
- ○passes all arguments through
- ○preserves this
- ○works when the callback is called synchronously
solution.jsExecutes in your browser
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.