用承诺处理分支
Handling branches with Promises
我对jQuery 1.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()
中无条件执行,但从不在第一种中执行,这变得更容易。
因此,第一个.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()
以这种方式运行。
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- keyup事件处理程序更改焦点不适用于快速键入
- 如何使用jquery处理php循环通过元素
- angular.js没有'无法在PhoneGap中处理视图标记
- Webpack/Rect:遵循egghead.io教程,但出现错误:您可能需要一个合适的加载程序来处理此文件类型
- 提示使用服务器端事件处理程序激活JavaScript
- javascript:如何在antlr生成的Lexer中进行错误处理
- 如何编写一个具有公共标头的批处理
- 在同一个服务工作者中处理service-worker.js有任何影响吗
- 如何处理node.js节点mongodb中的连接和查询队列
- 通过命令行/批处理文件打开页面时,将javascript代码注入Google Chrome
- 如何处理10页以上的静态页眉/页脚
- 将事件处理程序绑定到任何可能的事件
- 通过ajax将坐标传递到php服务器端,并在处理后检索到javascript
- python到“;流“;字典处理
- 使用javascript进行实时图像处理
- 导入jQuery脚本获胜'我不处理html文件
- Javascript无法处理表单提交
- 处理条if/else同时呈现两个分支
- 用承诺处理分支