DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

What is your opinion on callbacks in JavaScript?

Is it just the reminiscent of the Dark Ages past? Why are standard Node modules, and sometimes NPM full of these (e.g. sqlite3, nedb)?

When is it more preferable to Promises? What about not-yet-standard features, like Observable?

Do you use util.promisify often? What about ...Sync() functions (such as fs.readFileSync())?

Top comments (4)

Collapse
 
avalander profile image
Avalander

I always transform callback based APIs to use promises for convenience. That being said, people talk as if we were stuck in the stone age before promises but that's not true. A promise is basically a convenience structure to handle callbacks, and it is/was possible to write similar structures to handle callback APIs back in the days. It's just that most developers didn't bother because ¯\_(ツ)_/¯.

Regarding ...Sync functions, it depends. If I am writing a script to migrate a database, for instance, or doing some initialization when starting up a server, and the script/app can't do anything else until that operation is complete, using the ...Sync function makes the code slightly less convoluted and I prefer it. On the other hand, if the operation is used in an HTTP request handler, I want the app to be free to do other stuff while waiting for the operation, so I go for the asynchronous version.

Collapse
 
kigiri profile image
Clément

about Observable they serve a different purpose than promises and callbacks, It's a kind of event, it's good to react to changes of some state.

I've been using them a lot but less and less as they are a pain to debug and you end up trying to make everything into an observable to get ultra composability and it felt just too much at some point.

I use them sparsingly now, promises, always, and callback only to promisify.

Collapse
 
tobiassn profile image
Tobias SN

They often are that way for backwards compatibility, or simply because they haven’t been updated yet.

Collapse
 
farenheith profile image
Thiago Santos • Edited

Yeah, I agree.

Also, promises are always more preferable. Sync functions should be avoided in most cases, specially in browser js. When I'm programming in node, sometimes I use fs sync functions for the sake of simplicity, when I'm writing a cli code or the initialization of a server. Never in code that'll run concurrently.