4 ms·
Ask HN: Nowadays, should I make my js use callbacks, promises, or other?
Say I'm making javascript library that needs to do some asynchronous work. What is the current modern best practice?
getusermedia and jquery use callbacks, but it seems like that fell out of favor a while ago (or have callbacks come full circle and are preferred again?).
WebCrypto uses promises. Is that now what everyone is using for new libraries, or have people grown tired of promises?
XMLHttpRequest uses listeners (or whatever they are called: .onreadystate, etc.) which I guess are kind of like callbacks or events? Has that technique started to gain favor again?
Inter-iframe communication (postMessage) and bootstrap (for CSS transitions) use event listeners. Are events now a better way to signal when an asynchronous task is done?
I haven't kept up with all the latest preferred way to do this.
- lioeters 9y agoBetween callback functions and promises, I've seen a general shift toward preferring promises, as you said, even for native DOM APIs. Using then/catch/finally or async/await is easier to work with, I think, especially for a series of async actions. Event emitters are for a different range of use cases, I'd say: when you're expecting to send/receive a number of events, or multiple event types - for a duration of time, possibly open-ended like AJAX or WebSocket connection.