【问题标题】:Handling branches with Promises使用 Promises 处理分支
【发布时间】:2013-03-10 05:02:45
【问题描述】:

我对 jQuery 1.9.1 Promise 有疑问,我可能需要返回另一个 deferred 的条件逻辑,但我不知道如何处理它。这是我最好的尝试,但正如下面的 cmets 所示,当我点击 else 分支时,我仍然点击了第二个 .then() 函数,我希望我可以返回给用户。如何处理这种情况的任何模式?

storage.provision(c)

.then(function(rc){
    if(rc === 0){
        storage.write(c);
    }else{
        return options.onSuccess(rc); //how i got back to the users callbacks/promise, but this
        //takes me to the .then below
    }
})
 //storage.write returns a promise as well, do I do another .then 
// like this?
.then(function(rc){
    //I was hoping this would catch, the storage.write() case, and it does, but it also catches
    //the retun options.onSuccess(rc) in the else case.
    options.onSuccess(rc);
})


.fail(function(e){
    //handle error using .reject()
});

【问题讨论】:

  • 这篇文章可能对你有所帮助:stackoverflow.com/questions/12149993/…
  • This post 将帮助您更好地理解承诺。一般来说,如果你想使用条件,你应该将承诺保存为一个变量并在你的条件中执行你的thensuccessfail,你似乎在做相反的事情。

标签: javascript jquery asynchronous promise


【解决方案1】:

如果认为options.onSuccess(rc); 在第二个.then() 中无条件执行,但从不在第一个中执行,这将变得更容易。

因此,第一个.then() 必须传递rc

  • 如果rc === 0,响应storage.write(c)完成
  • 如果rc !== 0,则立即。

.then() 对此非常方便,因为它自然允许从其done 回调中返回新 Promise 的值。

storage.provision(c).then(function(rc) {
    if(rc === 0) {
        var dfrd = $.Deferred();
        storage.write(c).done(function() {
            dfrd.resolve(rc);
        }).fail(dfrd.fail);
        return dfrd.promise();
    } else {
        return rc;//pass on rc to the second .then()
    }
}).then(function(rc){
    options.onSuccess(rc);
}).fail(function(e){
    //handle error using .reject()
});

我确信存在其他方法,但这是我能想到的最接近您的原始概念的方法。

rc === 0 时不必创建新的 Deferred 会很好,但这是传递 rc 的最现实的方法,无需修改 storage.write() 以使其行为。

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 2014-05-27
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多