我想并行运行方法A和B,一旦它们都完成了,我想运行方法C。
如何使用可观察的javascript实现这一点?
main() {
this.methodA();
if(some_condition) this.methodB();
this.methodC();
}
methodA() {
setTimeout( () => { console.log("doing some work A"); }, 500);
}
methodB() {
setTimeout( () => { console.log("doing some work B"); }, 250);
}
methodC() {
console.log("should be the last...");
} 预期输出(如果some_condition为假):
做一些工作
应该是最后一个..。
预期输出(如果some_condition为真):
做一些工作
做一些工作
应该是最后一个..。
预期输出(如果some_condition为真):
做一些工作
做一些工作
应该是最后一个..。
发布于 2017-07-11 18:58:25
正如@CozyAzure所说,Observable.if()是你想要的。确保使用Observable.merge()和Observable.concat()。
const methodA = () => Observable.timer(500).mapTo("doing some work A")
const methodB = () => Observable.timer(250).mapTo("doing some work B")
const methodC = () => Observable.of("should be the last...")
const main = (some_condition) =>
Observable.if(
() => some_condition,
methodA().merge(methodB()),
methodA()
)
.concat(methodC())
.subscribe(console.log)
main(true)下面是小提琴中的示例
如果你在履行承诺,你可能想推迟你的承诺的产生。例如,
const methodA = () => Observable.timer(500).mapTo("doing some work A")
const methodB = () => Observable.timer(250).mapTo("doing some work B")
const methodC = () => Promise.resolve("should be the last...")
Observable.merge(methodA(), methodB())
.concat(Observable.defer(() => methodC())
.subscribe(console.log)https://stackoverflow.com/questions/45038940
复制相似问题