首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >可观察的等待方法完成

可观察的等待方法完成
EN

Stack Overflow用户
提问于 2017-07-11 15:35:54
回答 5查看 1.9K关注 0票数 0

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

如何使用可观察的javascript实现这一点?

代码语言: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为真):

做一些工作

做一些工作

应该是最后一个..。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-07-11 16:05:57

虽然我同意您的规范似乎最好使用承诺来完成,但我想我会用可观察的方法给您一个答案,看看您是如何要求的。

本质上,只需使用merge操作符,使methodA()methodB()返回可观测值,并在它们都完成时调用methodC()

代码语言:javascript
复制
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()

这个日志:

代码语言:javascript
复制
doing some work B
doing some work A
should be the last...
票数 2
EN

Stack Overflow用户

发布于 2017-07-11 15:43:18

最好的选择是使用一个承诺,它允许函数异步运行,然后在函数完成后触发一些函数。这里的好处是可以组合承诺,以便在完成某些工作之前等待它们中的任何一个或全部解决。

票数 1
EN

Stack Overflow用户

发布于 2017-07-11 15:46:44

使用ES7s异步函数/等待:

代码语言:javascript
复制
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();

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45038940

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档