Convert Callback Based Function to Promise Based Function — LeetCode 2776 Python Solution
MediumLeetCode PremiumJavaScript
- Problem
- #2776
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Example
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);
}
}Python solution
Python
import asyncio
def promisify(fn):
async def wrapped(*args):
loop = asyncio.get_running_loop()
future = loop.create_future()
def callback(value=None, err=None):
if future.done():
return
if err is not None:
future.set_exception(err)
else:
future.set_result(value)
fn(callback, *args)
return await future
return wrappedComplexity
| Measure | Complexity |
|---|---|
| Time | O(1) excluding the wrapped function |
| Space | O(1) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 2776. Convert Callback Based Function to Promise Based Function?
- LeetCode 2776. Convert Callback Based Function to Promise Based Function is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2776. Convert Callback Based Function to Promise Based Function?
- The Python solution on this page runs in O(1) excluding the wrapped function.
- What is the space complexity of LeetCode 2776. Convert Callback Based Function to Promise Based Function?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2776. Convert Callback Based Function to Promise Based Function cover?
- LeetCode 2776. Convert Callback Based Function to Promise Based Function is tagged JavaScript on LeetCode.
- Is LeetCode 2776. Convert Callback Based Function to Promise Based Function a premium problem?
- Yes. LeetCode 2776. Convert Callback Based Function to Promise Based Function is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.