打字稿异步等待运算符承诺和记忆模式
typescript async await operators promises and memoization pattern
我正在尝试使用最新的 TypeScript 增强功能使我的一些代码现代化。
我们有很多记忆模式。 想法是某些服务有多个订阅者,我们希望确保每个人都在等待一个呼叫而不是触发多个呼叫。
代码看起来像这样
private isAdmin: Promise<Boolean>;
public IsCurrentUserAdmin(): Promise<Boolean> {
if (!this.isAdmin) {
this.isAdmin = httpService.goGetTheData().then((data) => //do something and return Boolean);
}
return this.isAdmin;
我的问题是:类似的东西会和等待运算符 I "don't have access to the promise object" 有相同的效果吗?
public IsCurrentUserAdmin(): Promise<Boolean> {
const isAdminData = await httpService.goGetTheData();
// do something with the data to get the value
return isAdmin;
}
不,您绝对需要访问 promise 对象以进行记忆。 async
/await
不一定会阻止这种情况 - 它只是 then
调用的语法糖 - 但在您的特定情况下它并没有真正的帮助。由于您没有缓存 goGetTheData()
承诺,而是 .then(…)
返回的承诺(因此 "do something" 也只执行一次),您需要为那:
private isAdmin: Promise<boolean>;
private async fetchIsAdmin(): Promise<boolean> {
const data = await httpService.goGetTheData();
// do something and
return // a boolean
}
public IsCurrentUserAdmin(): Promise<boolean> {
if (!this.isAdmin) {
this.isAdmin = this.fetchIsAdmin();
// you could `await this.isAdmin` in here as well, but that would happen for every call
return this.isAdmin;
}
我正在尝试使用最新的 TypeScript 增强功能使我的一些代码现代化。
我们有很多记忆模式。 想法是某些服务有多个订阅者,我们希望确保每个人都在等待一个呼叫而不是触发多个呼叫。
代码看起来像这样
private isAdmin: Promise<Boolean>;
public IsCurrentUserAdmin(): Promise<Boolean> {
if (!this.isAdmin) {
this.isAdmin = httpService.goGetTheData().then((data) => //do something and return Boolean);
}
return this.isAdmin;
我的问题是:类似的东西会和等待运算符 I "don't have access to the promise object" 有相同的效果吗?
public IsCurrentUserAdmin(): Promise<Boolean> {
const isAdminData = await httpService.goGetTheData();
// do something with the data to get the value
return isAdmin;
}
不,您绝对需要访问 promise 对象以进行记忆。 async
/await
不一定会阻止这种情况 - 它只是 then
调用的语法糖 - 但在您的特定情况下它并没有真正的帮助。由于您没有缓存 goGetTheData()
承诺,而是 .then(…)
返回的承诺(因此 "do something" 也只执行一次),您需要为那:
private isAdmin: Promise<boolean>;
private async fetchIsAdmin(): Promise<boolean> {
const data = await httpService.goGetTheData();
// do something and
return // a boolean
}
public IsCurrentUserAdmin(): Promise<boolean> {
if (!this.isAdmin) {
this.isAdmin = this.fetchIsAdmin();
// you could `await this.isAdmin` in here as well, but that would happen for every call
return this.isAdmin;
}