Thursday 15 June 2017

javascript - Deferred/promise confusion and implementation




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!'});

Answer



If I would like to implement deferred by myself, would this be a right way to do?



No, your code misses a few important points:




  • A promise/deferred represents one single outcome only. It's state must not be changed after it is settled (fulfilled or rejected).

  • No matter when a callback is installed, it will be executed as soon as possible with the result. Your code fails to do that when the result has already arrived.

  • No matter how many callbacks are installed, they all will be executed. Your code allows to store only a single callback.



You might want to have a look at this example implementation or How is a promise/defer library implemented?.



Also, for a promise you will want to implement an interoperable then method for chaining, whose behaviour is described in the Promises/A+ specification.




Does deferred counts as a behavioural pattern?




Yeah, you could count them as a mix of observer or visitor pattern.




What is the difference between deferred and promise?




In general, a deferred does provide the methods to fulfill or reject, while a promise is the interface to install the callbacks on (without the ability to resolve the promise). See What are the differences between Deferred, Promise and Future in JavaScript? for details.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...