Callback style to a Promise
A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.
The task
`fn` is a callback-style function: its last argument is a callback that it calls as `callback(error, value)`, with `error` set to `null` or `undefined` on success. Return a new function that takes the same arguments without the callback and returns a Promise. The Promise resolves with `value` on success, also when the value is falsy such as `0` or `""`, and rejects with `error` when one is passed. If `fn` itself throws, the Promise rejects with what it threw.
What this exercise teaches
The wrapper appends its own callback to the arguments and connects it to resolve and reject. Testing the error first is what keeps falsy results working. A throw inside the Promise executor turns into a rejection by itself, so a function that fails before it ever calls back is covered as well.
A hint if you get stuck
Return `(...args) => new Promise((resolve, reject) => ...)`. Inside, call `fn(...args, callback)` where the callback rejects when `error` is set and resolves with `value` otherwise. Decide on the error, not on the value.
Try it now, free, no account needed
Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.
Open this exerciseMore exercises in Async and functions
- A counter with private stateFree
- Sleep with a PromiseFree
- Retry a failing callFree
- Promise.all with a concurrency limitFree
- DebounceFree
- MemoizeFree
- Run only onceFree
- Pipe functions togetherFree
- Timeout wrapperFree
- Run tasks in sequenceFree
- ThrottleFree
- Curry a functionFree
- Event emitterFree
- LRU cacheFree
- Write your own Promise.allFree