Javascript 以承诺经营分行

Javascript 以承诺经营分行,javascript,jquery,asynchronous,promise,Javascript,Jquery,Asynchronous,Promise,我对jQuery1.9.1承诺有一个问题,我可能需要返回另一个延迟的条件逻辑,我不知道如何处理它。这是我最好的尝试,但正如下面的注释所示,当我点击else分支时,我仍然点击了第二个.then()函数,我希望我可以回到用户那里。如何处理这种情况有什么模式吗 storage.provision(c) .then(function(rc){ if(rc === 0){ storage.write(c); }else{ return options.on

我对jQuery1.9.1承诺有一个问题,我可能需要返回另一个延迟的条件逻辑,我不知道如何处理它。这是我最好的尝试,但正如下面的注释所示,当我点击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()
});

考虑到
options.onSuccess(rc)在第二个
中无条件执行。然后()
但在第一个中从不执行

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

  • 如果
    rc==0
    ,则响应
    存储。写入(c)
    完成
  • 如果
    rc!==0
.then()
非常方便,因为它自然允许从其
done
回调返回新承诺的值

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
时,不必创建一个新的延迟函数是很好的,但这是传递
rc
的最现实的方法,避免了修改
存储。write()
以这种方式工作。

这篇文章可能会帮助你:将帮助你更好地理解承诺。一般来说,如果您想使用条件,您应该将承诺保存为变量,然后在条件中执行
success
fail
,您似乎是在以另一种方式执行。