typescript async等待运算符promises和memoization模式

时间:2017-10-27 19:35:51

标签: typescript promise async-await memoization

我尝试使用最新的TypeScript增强功能对我的一些代码进行现代化改造。 我们有很多记忆模式。 我们的想法是,某些服务有多个订阅者,我们希望确保每个人都在等待一个电话,而且不会拨打多个电话。 代码看起来像那样

                if (this.MyQueryStatus.Equals(QueryStatus.Succeeded))
                {
                    #region IF Succeeded
                    #region Create Results DataTable
                    DataTable resultsTable = new DataTable("Results");
                    resultsTable.Columns.Add("Id");
                    resultsTable.Columns.Add("FullName");
                    resultsTable.Columns.Add("Foreground");
                    resultsTable.Columns.Add("Blink");
                    resultsTable.Columns.Add("Background");
                    resultsTable.Columns.Add("TypeDesc");
                    resultsTable.Columns.Add("MemoryUsage");
                    #endregion Create Results DataTable

                    foreach (var row in this.MyQueryResult.Rows)
                    {
                        #region ForEach Row
                        DataRow newRow = resultsTable.NewRow();
                        newRow["Id"] = row.Data[0].ToString();
                        newRow["FullName"] = row.Data[1].ToString();
                        newRow["Foreground"] = row.Data[2].ToString();
                        newRow["Blink"] = row.Data[3].ToString();
                        newRow["Background"] = row.Data[4].ToString();
                        newRow["TypeDesc"] = row.Data[5].ToString();
                        newRow["MemoryUsage"] = row.Data[6].ToString();
                        resultsTable.Rows.Add(newRow);
                        #endregion ForEach Row
                    }

                    dataGridViewResults.DataSource = resultsTable;
                    tabControlMain.SelectedTab = tabControlMain.TabPages["tabPageResults"];
                    #endregion IF Succeeded
                }

我的问题是:像这样的东西会产生与await运算符相同的效果吗?我不能访问promise对象"吗

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;

1 个答案:

答案 0 :(得分:2)

不,您绝对需要访问memo化的promise对象。 async / await并不一定能阻止它 - 它只是then来电的语法糖 - 但在您的特定情况下,它并没有真正帮助。由于您没有缓存goGetTheData()承诺,而是由.then(…)返回的承诺(因此&#34;做某事&#34;只执行一次),您需要为此写一个额外的辅助方法:

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;
}
相关问题