Convert callback to promise (JavaScript function)

less than 1 minute read

Say you have a function with the following signature, which requires a callback as argument:

someFunctionWithCallback(argOne, argTwo, callback)

To convert it to a Promise‘d function do:

function someFunctionWithPromise(argOne, argTwo) {
    return new Promise((resolve) => {
        someFunctionWithCallback(argOne, argTwo, resolve);
    });
}

That’s it.

Check a running demo here.

If you have an error callback as well

You really should handle errors. Say the signature is, then:

someFunctionWithCallback(argOne, argTwo, successCallback, errorCallback)

To convert it to a Promise‘d function do:

function someFunctionWithPromise(argOne, argTwo) {
    return new Promise((resolve, reject) => {
        someFunctionWithCallback(argOne, argTwo, resolve, reject);
    });
}

Consuming the Promise‘d function

Either:

someFunctionWithPromise(1, 2).then((successArgs) => {
    console.log("Success :) ", successArgs);
}).catch((errorArgs) => {
    console.log("Error :( ", errorArgs);
});

Or use async/await:

(async () => {
    
    try {
        let successArgs = await someFunctionWithPromise(1, 2);
        console.log("Success :) ", successArgs);
    } catch (errorArgs) {
        console.log("Error :( ", errorArgs);
    }
    
})();

And done deal.

Don’t forget to check the running demo.

Tags: , , ,

Categories:

Updated:

Leave a Comment