Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在类OOP中异步创建方法_Javascript_Typescript_Oop - Fatal编程技术网

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;
 }