我正在编写几个有效延迟对象的函数,这些函数依赖于其他延迟对象的不同组合.
function takesOneSecond() {
return $.Deferred(function(deferred) {
// Does something...
}).promise();
}
function takesOneMinute() {
return $.Deferred(function(deferred) {
// Does something...
}).promise();
}
function takesThreeMinutes() {
return $.Deferred(function(deferred) {
// Does something...
}).promise();
}
function mySwitchingFunction() {
return $.Deferred(function(deferred) {
// Does something here..
// Effectively chooses one of several other functions to call.
if(/* choose 1 second */) {
// We tie ourselves to the '1 second' function.
// Call that function.
takesOneSecond().done(function() {
deferred.resolve(); // If that's done, I'm done too.
}).fail(function() {
deferred.reject(); // If that failed, I've failed too.
});
} else if(/* choose 1 minute */) {
// Etc..
} else if(/* choose 3 minutes */) {
// Etc..
}
}).promise();
}
我正在写这段代码很多,没有其他方法可以制作延迟镜像或级联相同的“已解决”或“被拒绝”的另一种延迟状态吗?
takesOneSecond().done(function() {
deferred.resolve(); // If that's done, I'm done too.
}).fail(function() {
deferred.reject(); // If that failed, I've failed too.
});
解决方法:
我认为你根本不需要构建新的承诺.回到第一个承诺.
function mySecondFunction() {
// Does something here..
// Effectively chooses one of several other functions to call.
// In this case, assume I've just chosen the 'myFirstFunction' function.
// Call that function and return its promise
return myFirstFunction();
}
如果你想强调“同时”部分但可能用不同的值解决,你可以通过链接.then
创建一个新的:
function mySecondFunction() {
return myFirstFunction().then(function(resultOfFirst) {
// but ignore it and
return differentResult;
}); // errors will propagate automatically
}