如何在Angular中排队异步/同步功能?

时间:2019-04-02 06:23:15

标签: angular typescript

我需要在队列中执行多个功能,但是这些功能可能是同步,异步甚至是混合(两种)类型,例如:

option = 1; // variable

do1() { // sync
    console.log(`hello, world`);
}

do2() { // async
    this.someService(`example.come`).subscribe( x => {
        option = 2;
        console.log(x);
    }, err => {
        option = 3;
        console.error(err);
    }
}

do3() { // mixed type, sync and async
    if (option === 4) {
        console.log(`happy day`);
    } else {
        option = 6;
        do2(); // <-- async func
    }
}

我希望我可以这样编写非常干净的代码:

waitUntilFinish do1();
waitUntilFinish do3();
waitUntilFinish do2();

有可能吗?

1 个答案:

答案 0 :(得分:2)

function f1() {
return new Promise((resolve, reject) => {
    console.log('f1');
    resolve();
});
}

 function f2() {
     console.log('f2');
  }

f1().then(res => f2());

等待同步

If f1 is asynchronous and return a Promise, use async/await:

 async FUNC() {
   await f1();
   f2();
}