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)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!