Scriptdrill

Level 5: Async and functions Exercise 76 of 76 Free

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 exercise

More exercises in Async and functions