Typescript 为什么键入脚本';异步';方法在第一个';等待&x27;发生
为什么代码只在第一次等待之前在同一“堆栈”中执行Typescript 为什么键入脚本';异步';方法在第一个';等待&x27;发生,typescript,async-await,es6-promise,Typescript,Async Await,Es6 Promise,为什么代码只在第一次等待之前在同一“堆栈”中执行 class SomeSyncClass { async method(): Promise<void> { console.log('in start async'); await this.someotherMethod(); console.log('in finish async'); } someotherMethod(): void { } method2(): v
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();
但如果我删除wait,它将同步执行:
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();
这是异步等待式编程的预期行为 在这种方法中:
async method(): Promise<void> {
console.log('in start async');
await this.someotherMethod();
console.log('in finish async');
}
async方法():Promise{
log('in start async');
等待这个。someotherMethod();
log('in finish async');
}
第二个日志语句不能在第一个相同的时钟中执行,因为中间等待调用。它基本上被编译成如下内容:
async method(): Promise<void> {
console.log('in start async');
this.someotherMethod().then(result => {
console.log('in finish async');
})
}
async方法():Promise{
log('in start async');
this.someotherMethod().then(结果=>{
log('in finish async');
})
}
您可以看到,只有在解析了someotherMethod
之后,它才会调用第二条log语句
然而,由于异步等待规则,第二个变量根本没有被转换。事件虽然someotherMethod
返回一个承诺,但该承诺将被忽略并退出范围
这些规则与Typescript无关,直接嵌入到JavaScript运行时和ECMA规范中。您在JavaScript和Typescript中遇到的情况。将
wait
放在不是承诺的表达式之前
如果wait运算符后面的表达式的值不是承诺,则它将转换为已解析的承诺
使用async/await
的普通JavaScript:
下面的代码片段相当于原始的wait
示例。等待会使同步的func3()
表现得像是异步的,因为它已转换为已解析的Promise
constfunc3=()=>{}
常量func2=async()=>{
log('in start async');
//等待将同步func3封装在已解决的承诺中。
等待函数3();
log('in finish async');
}
常量func1=()=>{
console.log('before');
func2();
console.log('after');
}
func1()在第一个示例中,您必须等待这个.method()代码>以获得正确的结果。就像现在一样,当它到达时返回wait this.someotherMethod()代码>和它的其余部分在this.someotherMethod()之后执行代码>完成。
async method(): Promise<void> {
console.log('in start async');
await this.someotherMethod();
console.log('in finish async');
}
async method(): Promise<void> {
console.log('in start async');
this.someotherMethod().then(result => {
console.log('in finish async');
})
}