Convert Callback Based Function to Promise Based Function — LeetCode 2776 Python Solution

MediumLeetCode PremiumJavaScript
Problem
#2776
Reading time
4 min

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 wrapped

Complexity

MeasureComplexity
TimeO(1) excluding the wrapped function
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview