I have some older Node.js code that I\'m updating. In the process I\'m designing new modules to work with the old code. I\'m finding that now, as opposed to when I first wro
They both exist to solve the same problem, handle the result of an asnychronous function.
Callbacks tend to be more verbose and coordinating multiple asynchronous requests concurrently can lead to callback hell if you're not actively modularizing your functions. Error handling and tracing tends to be less straightforward and even confusing since there could be many Error objects that all go back to a single error further down the call stack. Errors, also need to be passed back to the original caller that can also lead to some head scratching when determining where the original Error was thrown if anonymous functions were used in the callback chain. One of the benefits of callbacks is that they are just plain old functions and don't require any additional understanding beyond knowing how an asynchronous operation works.
Promises are more common as they require less code, are more readable since they are written like synchronous functions, have a single error channel, can handle thrown errors and with util.promisify() being added in the latest version of Node.js, can convert Error-First Callbacks to promises. There's also async/await
which is making its way into Node.js now as well, and they also interface with Promises.
This is totally opinion based, so it really is about what you're most comfortable with but, Promises and async/await
are the evolution of the callback and enhance the asynchronous development experience. This isn't an exhaustive comparison by any means but rather, a high level look at both callbacks and promises.