What are the pros & cons of Javascript Promises vs jQuery Deferred Objects?
For example, what issues do they each have, if any?
A fellow stack overflow member stated:
"...real promises are real, and fake promises are fake."
What did he mean by this?
There is no such thing as a "real promise" or a "fake promise". There are promise implementations that follow the current standards and there are promise implementations that do not follow the current standards. There is no inherent attribute of a promise that says it's "real" or "fake". They are bits of Javascript that implement a standard behavior.
Any promise implementation that rigorously follows the standard should be fine to use and should be interoperable with other standard promise implementations. Most will consider interoperability and adherence to accepted standards a useful characteristic.
Now, jQuery promises do not follow the promise standards which is where some people talk bad of jQuery promises. They are apparently working on making them more standard for a future version of jQuery, but they currently deviate from the standards in many ways. This leads to issues in that you have to code differently when using jQuery promises than when using standards promises. So jQuery promise code does not look the same as ES6 promise code.
Problems in jQuery Promises
See this reference for a list of problems with the current jQuery promises. The two main ones are a problem with error handling in rejected promises and an inconsistency in execution order of .then()
callbacks which can lead to unpredictable or inconsistent code execution. All .then()
handlers are supposed to be executed async (after the current thread of JS unwinds). jQuery promises do not always do this and it can cause problems in some types of code.
State of Native Promises in Browsers
Native promises are a somewhat new thing in browsers, so it's not yet the case that you can just rely on the fact that all browsers that might hit your site will necessarily have native promises built in. Native promises are built into browsers starting with Safari 7.1, Firefox 29, Chrome 32, Edge, Android 4.4.4, IOS 8.4 and not available yet in IE (as of Sept, 2015). So, you still need a fairly recent browser in order to have native promise support. As such, there are many excellent promise libraries that can offer either a polyfill or a full-on replacement, thus giving your code the ability to use promises in any browser with really no compromise vs. native promises.
JavaScript Promises are better because it conforms to the standard. One day they will be available on all browsers natively. For now you can use something like babel to use ES6 Promises today: https://babeljs.io/docs/learn-es2015/#promises.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With