首页 > 解决方案 > 在类 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 asynchronously
    this._goIn = true;
  }
  
  setName(name: string) {
    return this._name = name;
  }
}

我想要做的是将_goIn值异步更改为true。

最好的

标签: javascripttypescriptoop

解决方案


如果将代码执行推迟到调用堆栈被清空之后就足够了,那么:

return Promise.resolve().then(() => this._goIn = true);

class Activity {
  _name
  _goIn
  
  constructor(name) {
    this._name = name;
    this._goIn = false;
  }

  isGoIn() {
    return this._goIn;
  }
  
  setGoIn() {
    return Promise.resolve().then(() => this._goIn = true);
  }
  
  setName(name) {
    return this._name = name;
  }
}

// demo
let act = new Activity("test");
act.setGoIn().then(() => console.log("2. Asynchronous... now it is", act.isGoIn()));
console.log("1. Synchronous... now it still is", act.isGoIn());

或与async语法相同:

async setGoIn() {
    await null;
    this._goIn = true;
}

class Activity {
  _name
  _goIn
  
  constructor(name) {
    this._name = name;
    this._goIn = false;
  }

  isGoIn() {
    return this._goIn;
  }
  
  async setGoIn() {
    await null;
    this._goIn = true;
  }
  
  setName(name) {
    return this._name = name;
  }
}

// demo
let act = new Activity("test");
(async function() {
    await act.setGoIn();
    console.log("2. Asynchronous... now it is", act.isGoIn());
})(); // execute immediately
console.log("1. Synchronous... now it still is", act.isGoIn());

如果您有权访问queueMicroTaskor setTimeout,那么这些是非承诺解决方案:

return setTimeout(() => this._goIn = true);

setTimout返回超时的 id,但是当回调被执行时这没有给出任何线索。queueMicroTask返回未定义。从这个意义上说,Promise 解决方案是更好的做法:您可以在await表达式中使用返回的值,或者链接then对它的调用。


推荐阅读