Promisify a callback API
Plenty of libraries still take a callback as their last argument and call it with (error, value). Mixing that style with async/await is painful, so the usual fix is a small adapter written once.
Implement promisify(fn). It returns a new function that takes the same arguments as fn minus the trailing callback, and returns a Promise. Call fn with those arguments plus a callback of your own. When that callback receives a truthy first argument, reject with it. Otherwise resolve with the second argument, which may be undefined if the callback was called with only the error slot.
What it has to do
- The returned function always returns a
Promise. - Forward every argument it is given to
fn, in order, before the callback. - Resolve with the callback's second argument when the first is falsy.
- Reject with the callback's first argument when it is truthy.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.