你能解释为什么异步匿名函数不工作,而与“then”相同的构造按预期工作吗?
class TestClass {
constructor() {
this.init();
}
init () {
console.log ('1');
const result = async () => {
await this.wait2Seconds(); console.log ('333');
} // This not working !! We never see 333. Why ?
//this.wait2Seconds().then( (result) => {console.log ('22')}); // This works and we wait 2 seconds
console.log ('3');
}
async wait2Seconds () {
return new Promise(resolve => {
setTimeout(() => {
resolve('2');
}, 2000);
});
}
}
结果: 1个 3
如果我使用“then”结构,结果是: 1个 3个 22