In playing with Deferred's I see many different combinations of use. Most are the same, but occasionally I see ones that differ slightly.
FOR EXAMPLE...
NORMALLY, I SEE THIS:
Here we are merely using the Deferred.
// NORMALLY I SEE THIS...
function doSomething(){
var deferred = $.Deferred();
var myClass = new MyClass();
myClass.doSomething(function () {
deferred.resolve();
});
return deferred.promise();
};
OCCASSIONALLY, I SEE THIS:
Here we are passing a function into the Deferred's constructor...then using it.
// SOMETIMES I SEE THIS...
function doSomething() {
var deferred = $.Deferred(function (deferred) {
//Q: Is there an advantage to doing this instead?
//Q: Is this a mis-use?
var myClass = new MyClass();
myClass.doSomething(function () {
deferred.resolve();
});
});
return deferred.promise();
};
MY QUESTION IS:
I have yet to see any issue's arise from method 2. So, I'm looking for real insight here.
答案 0 :(得分:2)
Is there an advantage to doing the 2nd one instead?
No, unless you enjoy callbacks which defeats the purpose of promises.
Is this a mis-use of the constructor?
Nope. jQuery deffered doc
jQuery.Deferred( [beforeStart ] )
beforeStart Type: Function( Deferred deferred ) A function that is called just before the constructor returns.
Does this practice create issue I just haven't seen yet?
No it doesn't, unless you intended to use myClass
somewhere else which won't be possible since it is defined within your callback.
Conclusion:
In the end, it's more of a personal preference. Solution 1 just seems more clean to be honest.