I looked up for an answer on the internet but I could not really find what I was looking for.
I need to know what is wrong with the following code (provided we should avoid mixing callbacks and promises) -
function a(callback){
(async ()=>{
try{
let result = await doSomething();
callback(null, result);
} catch(e){
log('error at await');
callback(e, null);
}
})()
}
Is it ok if I use the above pattern in my code?
Can I mix callbacks and async/await patterns in NodeJS?
You can. It is not recommended.
It is generally more difficult to do proper error handling when mixing callbacks and promises. In addition, flow of control can be a real mess. This example isn't too messy because there's just one asynchronous operation, but why not just return a promise and join the modern age of asynchronous design and skip using any plain callbacks at all? Further, the await here is pretty pointless. You've just made things a lot more complicated than return doSomething()
and have the caller use the returned promise.
So, you could replace 9 lines of function body (including an async
IIFE) with 1 simple line.
Reasons not to mix plain callbacks and promises
async
library had to exist when we only had plain callbacks) whereas that level of flow control is natural and built-in with promises. Then, try mixing the two models of flow of control and error handling and things get real complicated quickly.await
shortly and probably even asynchronous imports based on promises. Why would you add in a complication to use an old model that is no longer considered the present or future of the language.util.promisify()
) and then using them only in their promise form for your actual implementation and control flow.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With