简体   繁体   English

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

[英]How to queue async/sync functions in Angular?

I need to execute several functions in a queue, but the functions may be sync, async, or even mixed (both) type, such as: 我需要在队列中执行几个功能,但是这些功能可能是同步,异步甚至是混合(两种)类型,例如:

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
    }
}

I hope I can write a very clean code as such: 我希望我可以这样编写一个非常干净的代码:

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

Is it possible? 可能吗?

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

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

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

WITH ASYNC AWAIT 使用异步等待

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

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

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

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