What I think people sometimes forget about async/Promises vs callbacks is that callbacks-style define a code structure that is hard to maintain by multiple developers, since it leaves a lot of power to the way you write your code. Not every team has 5 experienced JS developers, so at one point implementing a small feature by a team member would become : `Hey, let's just nest another callback in there. It takes 1 line of code` instead of implementing it in a readable way.
Promises solve this, but indeed there are a couple of problems there with debugging. Honestly I think they give more readable code than whatever callback implementation you invent to avoid the callback hell. Libraries as bluebird can make your promise operations really short and even one liners, without performance hit.
Finally now we have async, which I hope will be popular enough in the future to become at least as much popular as Promises are now.
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.
Exactly. 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.
Promises solve this, but indeed there are a couple of problems there with debugging. Honestly I think they give more readable code than whatever callback implementation you invent to avoid the callback hell. Libraries as bluebird can make your promise operations really short and even one liners, without performance hit.
Finally now we have async, which I hope will be popular enough in the future to become at least as much popular as Promises are now.