我想并行运行方法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 16:05:57
虽然我同意您的规范似乎最好使用承诺来完成,但我想我会用可观察的方法给您一个答案,看看您是如何要求的。
本质上,只需使用merge操作符,使methodA()和methodB()返回可观测值,并在它们都完成时调用methodC():
var some_condition = true
function main() {
let test$ = a()
if (some_condition) test$ = test$.merge(b())
test$.subscribe(console.log, null, c)
}
function a() {
return Rx.Observable.timer(500)
.mapTo('doing some work A')
}
function b() {
return Rx.Observable.timer(250)
.mapTo('doing some work B')
}
function c() {
console.log('should be the last...')
}
main()这个日志:
doing some work B
doing some work A
should be the last...发布于 2017-07-11 15:43:18
最好的选择是使用一个承诺,它允许函数异步运行,然后在函数完成后触发一些函数。这里的好处是可以组合承诺,以便在完成某些工作之前等待它们中的任何一个或全部解决。
发布于 2017-07-11 15:46:44
使用ES7s异步函数/等待:
async function main() {
await this.methodA();
if(true || some_condition) await this.methodB();
await this.methodC();
}
async function methodA() {
console.log("doing some work A");
await timer(1000);
console.log("finished A");
}
async function methodB() {
console.log("doing some work B");
await timer(1000);
console.log("finished B");
}
async function methodC() {
console.log("should be the last...");
}
function timer(time){
return new Promise(function(res){
setTimeout(res,time);
});
}
main();
https://stackoverflow.com/questions/45038940
复制相似问题