javascript - 在类 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。
最好的
解决方案
如果将代码执行推迟到调用堆栈被清空之后就足够了,那么:
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());
如果您有权访问queueMicroTask
or setTimeout
,那么这些是非承诺解决方案:
return setTimeout(() => this._goIn = true);
setTimout
返回超时的 id,但是当回调被执行时这没有给出任何线索。queueMicroTask
返回未定义。从这个意义上说,Promise 解决方案是更好的做法:您可以在await
表达式中使用返回的值,或者链接then
对它的调用。
推荐阅读
- bash - 如何检测 docker run 和底层守护程序是否以编程方式完全启动?
- c# - 在 ASP.NET Core 2.2 和 ASP 之间共享 Cookie 身份验证。没有 Microsoft.Identity 的 NET MVC 5 (.NET Framework 4.6.1)
- django - 使用 Django 模型中的字段对数据进行计算
- junit - 如何在扩展中使用 TempDir
- css - .SCSS 文件中的数学计算 Angular CLI 不起作用
- php - 如何在同一服务器上的 Web 应用程序(核心 PHP)和另一个 Web 应用程序(Laravel)之间共享会话?
- python-2.7 - 将运行时数据存储到 CSV 文件
- azure-active-directory - 针对 Azure AD 进行身份验证的问题
- javascript - 将图像从视频 JS 保存到画布
- javascript - 拖动一个元素但放下一组其他元素