@Domenic有一篇关于jQuery延迟对象失败的非常详尽的文章:你错过了Point of Promises.在其中,Domenic突出了jQuery承诺的一些失败,与其他包括Q,when.js,RSVP.js和ES6承诺相比.
我离开了Domenic的文章,认为jQuery承诺在概念上有一个固有的失败.我试图把这个例子放在这个概念上.
我认为jQuery实现有两个问题:
.then方法不可链接换一种说法
promise.then(a).then(b)
Run Code Online (Sandbox Code Playgroud)
jQuery将调用a随后b的时候promise满足.
由于.then在其他promise库中返回一个新的promise,它们的等价物将是:
promise.then(a)
promise.then(b)
Run Code Online (Sandbox Code Playgroud)
另一个问题似乎是异常处理,即:
try {
promise.then(a)
} catch (e) {
}
Run Code Online (Sandbox Code Playgroud)
Q中的等价物是:
try {
promise.then(a).done()
} catch (e) {
// .done() re-throws any exceptions from a
}
Run Code Online (Sandbox Code Playgroud)
在jQuery中,当acatch块失败时异常抛出并出现气泡.在其他承诺中,任何异常a将被传递到.done或.catch或其他异步捕获.如果没有任何promise API调用捕获异常,它就会消失(因此Q最佳实践,例如使用.done释放任何未处理的异常).
上述问题是否涵盖了jQuery实现承诺的问题,还是我误解或遗漏了问题?
编辑 此问题与jQuery <3.0; 从 jQuery 3.0开始,alpha jQuery是Promises/A +兼容的.
我有jQuery 1.9.1 promises的问题,我可能需要条件逻辑,它将返回另一个延迟,我不知道如何处理它.这是我最好的尝试,但正如下面的评论所示,当我点击其他分支时,我仍然按下第二个.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()
});
Run Code Online (Sandbox Code Playgroud)