[gist https://gist.github.com/vanduc1102/5e2e7cea325e628ad91fa11f6170d7a1]
But life is not that easy; sometimes a task needs more effort to be done.
Let assumed our task splits into three tasks now:
[gist https://gist.github.com/vanduc1102/b63a58ef1751d231d9111339be09df46]
In other to finish a task we need a callback hell (http://callbackhell.com/):
[gist https://gist.github.com/vanduc1102/f679b6039afd1ba893b310ace5b93e87]
Gather all snippets together:
[gist https://gist.github.com/vanduc1102/b22979ea867d47777e413c0831402fef]
Result:

In reality, a task may need more and more sub-tasks, the nesting will be super crazy.
Now we speak about Promise. Let convert our simple task from callback to promise
[gist https://gist.github.com/vanduc1102/523f1ffb2dccb9cc80f49de2d79e5611]
And then we will use Promise chaining to solve the callback hell issue.
[gist https://gist.github.com/vanduc1102/0b03c51edd629f05e1ddec95c7a288a8]
The result:

Conclusion: To be honest I don't see my example has a clear explanation about Promise over Callback Hell, but you have to trust me, you will see Promise very helpful later.
[…] Hi there here is the third post of Javascript/NodeJs callback. […]
ReplyDelete