gpt4 book ai didi

javascript - 如何使 jQuery Deferred 对象解析/拒绝具有与另一个 deferred 相同的 'resolved/rejected' 状态?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:47 25 4
gpt4 key购买 nike

我正在编写几个函数,这些函数实际上是依赖于其他延迟对象的不同组合的延迟对象。

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.
});

最佳答案

我认为你根本不需要构建一个新的 promise 。只需返回第一个 promise 即可。

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
}

关于javascript - 如何使 jQuery Deferred 对象解析/拒绝具有与另一个 deferred 相同的 'resolved/rejected' 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com