JSFiddle - React, Tailwind, and code Playground
by danheberden
HTML
Check console for output if you don't trust the commments
JavaScript
/* In promises/A, .then always returns a new Deferred. This is
neat for the below example, but doesn't work with a system
that doesn't swallow exceptions because returning falsy or truthy
could be a legitimate value.
*/
console.log('returning a plain value');
var dfd = $.Deferred();
dfd.then(null, function(a, b){
return a * b;
}).then(function(value){
// jQuery won't fire this success callback
console.log(value, 'should be 6');
}, function(value){
// jQuery is still operating on dfd
console.log(value, 'REJECTED');
});
dfd.reject(2, 3);
/* jQuery *will*, however, turn things around if you return a
promise - effectively allowing you to chain promises. */
console.log('\n', 'returning a new promise');
var dfd = $.Deferred();
dfd.then(null, function(a, b){
var d = $.Deferred();
d.resolve(a * b);
return d.promise();
}).then(function(value){
// jQuery will fire this success callback
console.log(value, 'should be 6');
}, function(value){
// jQuery is now operating on the piped promise
console.log(value, 'REJECTED');
});
dfd.reject(2, 3);
/* What I suggest is a helper utility to instantly resolve
or reject values. That could be presented in two ways: */
console.log('\n', 'returning $.Deferred.resolve');
$.Deferred.resolve = function() {
var dfd = $.Deferred();
dfd.resolve.apply(this, arguments);
return dfd.promise();
};
$.Deferred.reject = function() {
var dfd = $.Deferred();
dfd.reject.apply(this, arguemnts);
return dfd.promise();
};
var dfd = $.Deferred();
dfd.then(null, function(a, b){
// yay simpler
return $.Deferred.resolve(a * b);
}).then(function(value){
// jQuery will fire this success callback
console.log(value, 'should be 6');
}, function(value){
// jQuery is now operating on the piped promise
console.log(value, 'REJECTED');
});
dfd.reject(2, 3);
/* Or, since something already exists like this with
$.when, expose $.unless that does the opposite...