繁体   English   中英

可观察的等待方法完成

[英]Observable wait for a method to complete

我想并行运行方法A和B,一旦它们都完成,我想运行方法C。

如何使用Observable在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为false):

做一些工作A

应该是最后一个...

预期输出(如果some_condition为true):

做一些工作

做一些工作B

应该是最后一个...

预期输出(如果some_condition为true):

做一些工作B

做一些工作

应该是最后一个...

虽然我同意似乎可以最好地使用诺言来完成您的规范,但我想我会使用Observables给您一个答案,看看您的要求是什么。

本质上,只需使用merge运算符,使methodB() 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...

最好的选择是使用Promise ,它允许异步运行功能,然后在完成时触发某些功能。 这样做的好处是可以组成承诺,这样您就可以在完成某些工作之前等待它们中的任何一个或全部解决。

使用ES7的异步功能/等待:

 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(); 

人们可能会忘记Observable.if()的隐藏的宝石。

Observable.if(condition, thenSource, [elseSource])接受3个参数。 第一个参数是布尔条件,第二个参数是条件为true时要发出的Observable,最后一个参数是else源的数组,如果条件为false则将被发射。

如果要完全观察可观察到的代码,可以采用以下方法:

1.让所有方法都返回一个Observable

const methodA = () => {
    return Observable
        .timer(500)
        .do(() => {
            //do your work A here
            console.log('doing some work A');
        })
};

const methodB = () => {
    return Observable
        .timer(250)
        .do(() => {
            //do your work B here
            console.log('doing some work B');
        })
};

const methodC = () => {
    console.log("should be the last...");
};

2.使用Observable.if()解析流

现在,在您的主体中,只需使用Observable.if()来检查条件是否为true,并相应地发出Observable:

const main = () => {
    let some_condition = true;
    Observable
        .if(
            //a function that returns true or false
            () => some_condition,
            //Observable to emitif condition is true
            methodA().switchMap(() => methodB()),
            //Observable to emit if condition is false
            methodA()
        )
        .subscribe(() => {}, error => {}, methodC)
};

这是为您工作的JSBin

有关Observable.if()的更多信息: https : //github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/if.md

正如@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)

这是jsfiddle中的示例

如果您正在处理诺言,则可能要推迟创建诺言。 例如,

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM