Description

In older Node.js APIs, asynchronous functions use callbacks instead of Promises.
A typical Node-style function has its last argument as a callback, with the signature:


callback(error, result)


If the operation succeeds, the function calls callback(null, result).
If it fails, it calls callback(error).

Your task is to write a utility function promisify(func) that converts such callback-based functions into Promise-based ones.

Requirements

  • The returned function should:
    • Return a Promise.
    • Resolve with the result if the callback succeeds.
    • Reject with the error if the callback fails.
  • The original function’s this context and arguments must still work correctly.
  • You must not modify the existing function’s signature.

Example

// A sample callback-based function
function getData(id, callback) {
setTimeout(() => {
if (id > 0) callback(null, { id, name: "Item" });
else callback(new Error("Invalid ID"));
}, 100);
}

// Convert to a Promise-based function
const promisifiedGetData = promisify(getData);

promisifiedGetData(1)
.then(console.log) // { id: 1, name: "Item" }
.catch(console.error);

promisifiedGetData(-1)
.then(console.log)
.catch(console.error); // Error: Invalid ID


Hint 1

You’ll need to create a new Promise() that calls the original function with the same arguments, plus a callback that resolves or rejects the promise.

Hint 2

Don’t forget to preserve the this context when invoking the original function — use .call(this, ...) or .apply(this, ...).