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)
}
Hope this helps 😃
Top comments (0)