【发布时间】:2019-09-29 19:58:22
【问题描述】:
为什么只在第一次等待之前在同一个“堆栈”中执行代码?
class SomeSyncClass {
async method(): Promise<void> {
console.log('in start async');
await this.someotherMethod();
console.log('in finish async');
}
someotherMethod(): void { }
method2(): void {
console.log('before');
this.method();
console.log('after');
}
}
new SomeSyncClass().method2();
输出:
before
in start async
after
in finish async
但如果我删除 await - 它将同步执行:
class SomeSyncClass {
async method(): Promise<void> {
console.log('in start async');
this.someotherMethod();
console.log('in finish async');
}
someotherMethod(): void { }
method2(): void {
console.log('before');
this.method();
console.log('after');
}
}
new SomeSyncClass().method2();
输出:
before
in start async
in finish async
after
【问题讨论】:
-
在第一个示例中,您必须
await this.method();才能获得正确的结果。就像现在一样,它在到达await this.someotherMethod();时返回,其余部分在this.someotherMethod();完成后执行。
标签: typescript async-await es6-promise