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)