by xtrumanx · 11y ago · 0 comments
I learned about deferred a few years ago and kinda stuck with it. It's all over my code base and he didn't really justify why I should go about changing it. The only thing I can reason I can think of is using his recommendation follows the ES6 spec which doesn't matter to me that much for now.
One place this is mentioned is: https://github.com/petkaantonov/bluebird/wiki/Promise-anti-p...
According to the Promises/A+ spec, then should always return a new promise. With the jQuery deferred.then() that's not the case.
In practice this means that it's harder to recover from failures as you're processing your results because your all your onRejected callbacks are attached to the same deferred and so will all fire one after another.
If you're just dealing with one asynchronous event, for example an AJAX call, that might not be a problem but it can cause problems debugging more complex code if you're not very careful.
E.g. (Get request) -then-> (onGetSuccessProcessor, onGetReject) -then-> (onProcessSuccess, onProcessingReject)
If the get request fails the onProcessingReject will also execute even though we haven't run the onGetSuccessProcessor callback.
In Promises/A+ code you can return a new resolved promise from your onRejected callback and the next "then" will fire it's onResolve callback instead of onRejected.
Hope that helps. (it's a lot easier to draw as a petri net than to explain in a comment on HN :)
In jQuery 3.0, their Promises will be fully Promises/A+ compliant as long as you're using `.then` ( `.done` and `.fail` are remaining non-compliant to remain non-breaking with sync XHR I believe )
Edit: What I mean by "wiring" is that you need to make sure that in all successful code paths `deferred.resolve` is called and that in all erroneous code paths (not always a single try catch either) `deferred.reject` is called.