Javascript 在类OOP中异步创建方法
这是我的活动课Javascript 在类OOP中异步创建方法,javascript,typescript,oop,Javascript,Typescript,Oop,这是我的活动课 export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // how to set _goIn value to true async
export class Activity {
_name: string
_goIn: boolean
constructor(name: string) {
this._name = name;
this._goIn = false;
}
isGoIn() {
return this._goIn;
}
setGoIn() {
// how to set _goIn value to true asynchronously
this._goIn = true;
}
setName(name: string) {
return this._name = name;
}
}
我要做的是将\u goIn
值异步更改为true
最佳如果足够将代码执行延迟到调用堆栈清空之后,则:
return Promise.resolve().then(() => this._goIn = true);
课堂活动{
_名字
_戈因
建造师(姓名){
这个。_name=name;
这个.\u goIn=false;
}
isGoIn(){
把这个还给我;
}
setGoIn(){
返回Promise.resolve(),然后(()=>this.\u goIn=true);
}
集合名(名称){
返回此项。_name=name;
}
}
//演示
让act=新活动(“测试”);
然后(()=>console.log(“2.异步…现在是”,act.isGoIn());
log(“1.同步…现在仍然是”,act.isGoIn())代码>
记住在另一个异步函数中使用wait来获取值。希望这能有所帮助。您也可以尝试返回承诺而不是_goIn函数谢谢您的解释,我同意第一个。您的异步函数和原始承诺示例并不相同。它应该是async setGoIn(){await Promise.resolve();this.\u goIn=true;}是的,你完全正确,@DmitriyMozgovoy,我插入了一个await
。谢谢你的评论。
async isGoIn() {
return this._goIn;
}