DEV Community

Cover image for Promisify old callback functions
David Snyder
David Snyder

Posted on

1 2

Promisify old callback functions

Are you using a library that still uses callback functions for their asynchronous code and you want to await those functions? This problem is easy to solve by wrapping the function in a promise. Here is how you do it

//old method
doAsyncStuff("params", (err, result) => {
    if (err) {
        console.error(err);
    } else {
        console.log(result);
    }
});

// with promises
const doPromiseStuff = params =>
    new Promise((resolve, reject) => {
        doAsyncStuff(params, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });

// in an async function
try{
    const result = await doPromiseStuff("params")
}catch(err){
    console.error(err)
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps 😃

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay