按顺序执行异步函数,并等待每个函数完成
Executing asynchronous functions in order, and waiting for for every function to be finished
我需要按特定顺序执行一些异步函数,并等待每个函数完成。
我这样做:
public async init(): Promise<void> {
try {
this.executeFunction1().then(() => {
this.executeFunction2().then(() => {
this.executeFunction3().then(() => {
this.executeFunction4().then(() => {
this.executeFunction5();
});
});
});
});
} catch (error) {
this.log.error(`Init failed`);
}
}
所有函数都是异步的,如:
public async executeFunction1(): Promise<void> {
...........................
}
这是一个好方法(最佳实践)还是这种方法 'Ok'/'not advised' 但是还有更好的方法吗?
这是一个微不足道的 async
/await
案例。由于您已经在使用 async
,因此您缺少 await
。这样的事情会做:
public async init(): Promise<void> {
try {
await this.executeFunction1();
await this.executeFunction2();
await this.executeFunction3();
await this.executeFunction4();
await this.executeFunction5();
} catch (error) {
this.log.error(`Init failed`);
}
}
这种编程是引入 async
/await
的主要原因,以便以伪同步方式促进异步调用。
您可能想要这样的东西:
public async init(): Promise<void> {
try {
await this.executeFunction1();
await this.executeFunction2();
// etc ...
} catch (error) {
this.log.error(`Init failed`);
}
}
如果你想使用 RxJS,你可以使用 concat
创建方法:
import { concat } from 'rxjs';
concat(
this.executeFunction1(),
this.executeFunction2(),
this.executeFunction3(),
this.executeFunction4(),
this.executeFunction5(),
).subscribe();
我需要按特定顺序执行一些异步函数,并等待每个函数完成。 我这样做:
public async init(): Promise<void> {
try {
this.executeFunction1().then(() => {
this.executeFunction2().then(() => {
this.executeFunction3().then(() => {
this.executeFunction4().then(() => {
this.executeFunction5();
});
});
});
});
} catch (error) {
this.log.error(`Init failed`);
}
}
所有函数都是异步的,如:
public async executeFunction1(): Promise<void> {
...........................
}
这是一个好方法(最佳实践)还是这种方法 'Ok'/'not advised' 但是还有更好的方法吗?
这是一个微不足道的 async
/await
案例。由于您已经在使用 async
,因此您缺少 await
。这样的事情会做:
public async init(): Promise<void> {
try {
await this.executeFunction1();
await this.executeFunction2();
await this.executeFunction3();
await this.executeFunction4();
await this.executeFunction5();
} catch (error) {
this.log.error(`Init failed`);
}
}
这种编程是引入 async
/await
的主要原因,以便以伪同步方式促进异步调用。
您可能想要这样的东西:
public async init(): Promise<void> {
try {
await this.executeFunction1();
await this.executeFunction2();
// etc ...
} catch (error) {
this.log.error(`Init failed`);
}
}
如果你想使用 RxJS,你可以使用 concat
创建方法:
import { concat } from 'rxjs';
concat(
this.executeFunction1(),
this.executeFunction2(),
this.executeFunction3(),
this.executeFunction4(),
this.executeFunction5(),
).subscribe();