5 ms·
Even when implemented in a readable way, callbacks can still become hard to maintain. When you use properly separate functions (instead of anonymous ones), you
by dvlsg 10y ago
Even when implemented in a readable way, callbacks can still become hard to maintain. When you use properly separate functions (instead of anonymous ones), you typically have to embed those methods inside one another.
I'll take an example from the callbackhell website that was linked previously:
document.querySelector('form').onsubmit = formSubmit
function formSubmit (submitEvent) {
var name = document.querySelector('input').value
request({
uri: "http://example.com/upload",
body: name,
method: "POST"
}, postResponse)
}
function postResponse (err, response, body) {
var statusMessage = document.querySelector('.status')
if (err) return statusMessage.value = err
statusMessage.value = body
}
What happens when I want to do something other than `postResponse` when `formSubmit` is finished? I would have to start thinking about using partial application and providing specific callbacks, which is okay, but what if the callback levels are multiples deep? The code still starts to get muddy really quickly.
With promises / async, the asynchronous code doesn't need to know anything about what functions want to run afterwards, so the concerns stay completely separated.
- drinchev 10y agoExactly. You need to keep really good control over your code structure to avoid callback hell. And again at one point you will end up in a situation where you will need to declare functions inside a main function, etc. That's why I noted that I've never seen a callback implementation that is more readable than promises.