Convert Callback Based Function to Promise Based Function - Problem
Write a function that accepts another function fn and converts the callback-based function into a promise-based function.
The function fn takes a callback as its first argument, along with any additional arguments args passed as separate inputs. The promisify function returns a new function that should return a promise.
The promise should resolve with the argument passed as the first parameter of the callback when the callback is invoked without error, and reject with the error when the callback is called with an error as the second argument.
Example:
This callback-based function:
function sum(callback, a, b) {
if (a < 0 || b < 0) {
const err = Error('a and b must be positive');
callback(undefined, err);
} else {
callback(a + b);
}
}Should become equivalent to this promise-based function:
async function sum(a, b) {
if (a < 0 || b < 0) {
throw Error('a and b must be positive');
} else {
return a + b;
}
} Input & Output
Example 1 — Basic Function Conversion
$
Input:
fn = function(callback, a, b) { callback(a + b); }
›
Output:
Returns a function that returns Promise resolving to a + b
💡 Note:
The callback-based function is wrapped to return a Promise that resolves with the sum
Example 2 — Error Handling
$
Input:
fn = function(callback, a, b) { if (a < 0) callback(undefined, 'Error'); else callback(a + b); }
›
Output:
Promise rejects with 'Error' if a < 0, otherwise resolves with a + b
💡 Note:
Error passed as second parameter to callback becomes Promise rejection
Example 3 — Multiple Arguments
$
Input:
fn = function(callback, x, y, z) { callback(x * y * z); }
›
Output:
Promise resolves to x * y * z
💡 Note:
Function with multiple arguments still follows same pattern: callback becomes Promise
Constraints
- fn is a valid callback-based function
- The callback follows the pattern: callback(result, error)
- If error is undefined/null, the operation succeeded
- If error is provided, the operation failed
Visualization
Tap to expand
Understanding the Visualization
1
Input
Callback-based function fn(callback, ...args)
2
Process
Wrap in Promise constructor with resolve/reject
3
Output
Promise-based function returning Promise
Key Takeaway
🎯 Key Insight: Wrap callback functions in Promise constructor to modernize async code and enable async/await usage
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code