Advantages/Disadvantages 将函数传递给 Deferred 的构造函数
Advantages/Disadvantages of Passing a Function into Deferred's Constructor
在使用 Deferred 的过程中,我看到了许多不同的使用组合。大多数都是一样的,但偶尔我会看到一些略有不同的。
例如...
通常,我看到这个:
这里我们仅仅使用 Deferred.
// NORMALLY I SEE THIS...
function doSomething(){
var deferred = $.Deferred();
var myClass = new MyClass();
myClass.doSomething(function () {
deferred.resolve();
});
return deferred.promise();
};
偶尔,我看到这个:
这里我们将一个函数传递给 Deferred 的构造函数...然后使用它。
// 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();
};
我的问题是:
- 做第二个有好处吗?
- 这是构造函数的误用吗?
- 这种做法会产生我还没有遇到的问题吗?
我还没有看到方法 2 出现任何问题。所以,我正在寻找真正的见解。
Is there an advantage to doing the 2nd one instead?
不,除非你喜欢回调,这违背了 promises 的目的。
Is this a mis-use of the constructor?
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?
不,它不会,除非您打算在其他地方使用 myClass
,这是不可能的,因为它是在您的回调中定义的。
结论:
归根结底,这更多是个人喜好。老实说,解决方案 1 似乎更干净。
在使用 Deferred 的过程中,我看到了许多不同的使用组合。大多数都是一样的,但偶尔我会看到一些略有不同的。
例如...
通常,我看到这个:
这里我们仅仅使用 Deferred.
// NORMALLY I SEE THIS...
function doSomething(){
var deferred = $.Deferred();
var myClass = new MyClass();
myClass.doSomething(function () {
deferred.resolve();
});
return deferred.promise();
};
偶尔,我看到这个:
这里我们将一个函数传递给 Deferred 的构造函数...然后使用它。
// 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();
};
我的问题是:
- 做第二个有好处吗?
- 这是构造函数的误用吗?
- 这种做法会产生我还没有遇到的问题吗?
我还没有看到方法 2 出现任何问题。所以,我正在寻找真正的见解。
Is there an advantage to doing the 2nd one instead?
不,除非你喜欢回调,这违背了 promises 的目的。
Is this a mis-use of the constructor?
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?
不,它不会,除非您打算在其他地方使用 myClass
,这是不可能的,因为它是在您的回调中定义的。
结论:
归根结底,这更多是个人喜好。老实说,解决方案 1 似乎更干净。