I've been through a lot of posts over the web(and in SO) saying that it is not possible. However, I did the following code:
var a = {
_sum: 0,
_timer: null,
_resetTimer: function() {
if (this._timer) {
window.clearTimeout(this._timer);
}
this._timer = window.setTimeout(this._endChain.bind(this), 0);
},
_endChain: function() {
console.log(this._sum);
},
A: function() {
this._resetTimer();
this._sum+= 1;
return this;
},
B: function() {
this._resetTimer();
this._sum+= 2;
return this;
}
};
a.A().B().B().A();
I want to know how problematic this can be, if this is not encouraged to be used.
Edit:
A negative point is: if you need anything that would be processed by _endChain
you could not use return
, only with a promise or another timeout outside the whole chain. Example.
1 Answer 1
It's not problematic in the sense that _endChain
will always be called after the whole chain. In fact you could simplify the code by only creating the timer once:
var a = {
_timer: null,
_resetTimer: function() {
if (!this._timer)
this._timer = window.setTimeout(this._endChain.bind(this), 0);
},
But the problem will come with code that follows for example:
a.A().B().B().A();
DoMoreStuff();
Most developers would be surprised to find that the first call has not completed. I think the better solution would be to implement an end
method which is what many libraries do:
let result = a.A().B().B().A().end();
DoMoreStuff();
Or a promise like method:
a.A().B().B().A().then( function(result) {
DoMoreStuff();
});
-
\$\begingroup\$ So it could work in case of a lone method which the rest of the code doesn't depends on. \$\endgroup\$DontVoteMeDown– DontVoteMeDown2017年03月21日 18:54:50 +00:00Commented Mar 21, 2017 at 18:54