Problem Description
Given a callback-based function fn that receives a callback as its first argument (followed by any number of additional parameters), write a function promisify that converts fn into a promise-based version. The returned function should, when invoked, call the original fn with a callback that resolves the promise with the first parameter if no error is provided, or rejects the promise with the error provided as the second parameter if it exists.
Key Insights
- Wrap the execution of fn inside a promise.
- The callback passed to fn must analyze its arguments: if a second argument (error) exists, reject the promise; otherwise, resolve it.
- The returned promisified function should accept the same non-callback parameters as fn, and internally pass them along with the callback.
Space and Time Complexity
Time Complexity: O(1) per function call since we are simply wrapping the call in a new promise. Space Complexity: O(1) aside from the space used by the promise object and local variables.
Solution
We use a higher-order function that returns a new function wrapping the original callback-based function call inside a promise. When the returned function is invoked, it:
- Creates and returns a new promise.
- Defines a callback that will check if an error argument exists (indicating rejection) or not (indicating resolution).
- Calls the original fn, passing the callback as the first argument and forwarding any additional arguments. This pattern cleanly converts callback-based APIs into promise-based ones, enabling modern asynchronous patterns like async/await.