If I would like to implement deferred by myself, would it be a right way to do(trying to understand the internal logic):
Does deferred counts as a behavioural pattern?
What is the difference between deferred and promise?
function Deferred() {
var d = {},
f = {},
a = {},
state = 'pending';
return {
resolve: function(){
state = 'resolved';
a.fn.apply(a.context, arguments);
d.fn.apply(d.context, arguments);
},
reject: function(){
state = 'rejected';
a.fn.apply(a.context, arguments);
f.fn.apply(f.context, arguments);
},
done: function(fn, context) {
d = {fn: fn, context: context};
return this;
},
fail: function(fn, context) {
f = {fn:fn, context: context};
return this;
},
always: function(fn, context) {
a = {fn:fn, context: context};
return this;
},
state: state
}
}
Application example:
var obj = Deferred();
obj.done(function(arg){
console.log('we are done here. why? -', arg);
}, window)
.always(function(arg){
console.log('print that in any case. and some details:', arg);
}, window)
.fail(function(arg){
console.log('we failed here. why? -', arg);
}), window;
obj.reject('some arguments');
obj.resolve({argument: 'hooray!'});