【问题标题】:Q and promises chainingQ 和 Promise 链接
【发布时间】:2015-01-19 09:25:50
【问题描述】:
假设 A() 返回一个已解决的 Promise 并转到 B()。
但是,在某些情况下,我需要 B() 来完成而不是执行下一个 then() (我不想进入 C()。我可以在 B() 方法中使用 defered.reject() 但确实如此好像不对。
var p = pull(target)
.then(function (data) {
return A();
})
.then(function (data) {
return B();
})
.then(function (data) {
return C();
})
有什么提示吗?
【问题讨论】:
标签:
node.js
promise
q
chaining
【解决方案1】:
使用 Promise 进行分支的方式与不使用 Promise 的方式相同 - 主要通过 if 条件:
var p = pull(target)
.then(A).then(B)
.then(function (data) {
if(data) return C(); // assuming B's resolution value is a boolean
});
【解决方案2】:
把它包裹在同一个 then 方法中怎么样?
var p = pull(target)
.then(function(data) {
return A();
})
.then(function(data) {
var result = B();
if (!result)
return C()
return result;
})