MediumNo. 2776LeetCode Premium
Convert Callback Based Function to Promise Based Function — LeetCode 2776 Python Solution
- Topics
- JavaScript
- 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
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
- Time
- O(1)excluding the wrapped function
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 2778 | Sum of Squares of Special Elements | Easy |
| 0057 | Insert Interval | Medium |
| 0192 | Word Frequency | Medium |
| 0193 | Valid Phone Numbers | Easy |
| 0194 | Transpose File | Medium |
| 0195 | Tenth Line | Easy |
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.