RE: Asynchronous Programming in JavaScript: Promises
What is really interesting about promises (comparing to ordinary callback approach) is that you, as a developer, have a flow under your control. Within the callback you basically send your function reference to third party library, i.e.:
api.sync(cb)
Now imagine, your cb
function does sensitive data manipulation, even money transfers. So, are you 100% sure, that third party lib will call your callback only once? Perhaps it will be twice or more? Promises gives you some kind of inverted approach. You basically do not send the callback to third party library, so the whole flow is managed by you, only. What the library only does is call resolve
or reject
with operation result (as you provided in your example). They literally can't access your cb
function reference, to call it twice or even more.
What's more, Promises are designed in such way, that they must be called only once.
PS: Great article. You might also take a look on the Observables, as you are touching async flow management in your posts. Cheers.
Thank you, @adasq. You have provided good insights. I wrote a pub/sub module a few years back and I have been using it frequently, but I am not much familiar with observables. I'll have to read about it.