DEV Community 👩‍💻👨‍💻

Cover image for Promisify old callback functions
David Snyder
David Snyder

Posted on

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)

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.