3 ms·
I wrote a ton of callback-oriented code, thinking similarly to you. Promises have come a long ways since then, and I tried out Q.js and discovered that I was mi
by rictic 14y ago
I wrote a ton of callback-oriented code, thinking similarly to you. Promises have come a long ways since then, and I tried out Q.js and discovered that I was missing out on a significant and powerful abstraction. The two things you're missing out on here are:
#1 Promises have strong guarantees. A promise will be resolved at most once, and it will be either resolves successfully or unsuccessfully. This makes reasoning about them and composing them together much easier. For example, whenever I need to perform multiple async calls with callbacks I've always got to write a bit of repetitive error-prone boiler plate to wait for and combine their results. With a good promise library this is a one-liner using a well tested library function.
#2 Error propagation. With callbacks most exceptions vanish into the ether, only catchable by window.onerror and friends. Propagating that promise up to the caller who can handle it is an enormous pain in the ass and requires repetitive error handling code everywhere if you want to be resilient. With promises an exception raised in a handler counts as the resulting promise failing, which can propagate up similarly to the way exceptions propagate with try/catch. Again, this makes writing reliable abstractions so much easier.
- taproot 14y ago#2 cannot be emphasized enough, I can't count the number of times this would have improved my code in a huge way.
- rektide 14y agoThese two points seem to tack closely to the original article. They're certainly important characteristics about promises, but the fact that the promise is an object for the future, and can be composed and their exception handling can be composed, speaks to me of greatness. These things you mention are technical bullet points emphasizing components of that greater greatness.