Using TypeScript with async await operators, promises, and the memoization pattern

I am currently in the process of updating my code to incorporate the latest TypeScript enhancements. We have implemented various memoization patterns, with the main goal being to ensure that services with multiple subscribers wait for one call and do not trigger multiple calls simultaneously.
Here is a snippet of the code:

private isAdmin: Promise<Boolean>;
public IsCurrentUserAdmin(): Promise<Boolean> {
if (!this.isAdmin) {
this.isAdmin = httpService.goGetTheData().then((data) => //perform actions and return Boolean);
}
return this.isAdmin;

My query is: Will using something like this achieve the same result as with the await operator since I do not have direct access to the promise object?

public IsCurrentUserAdmin(): Promise<Boolean> {
const isAdminData = await httpService.goGetTheData();
// manipulate the data to obtain the desired value
return isAdmin;
}

Answer №1

It is essential to have access to the promise object for memoization. While using async/await may not prevent this, as it is essentially just a syntax shortcut for then calls, in your specific scenario, it may not be very helpful. This is because you are caching the promise returned by .then(…) instead of the initial goGetTheData() promise. To address this, you would need to create an additional helper method:

private isAdmin: Promise<boolean>;
private async fetchIsAdmin(): Promise<boolean> {
    const data = await httpService.goGetTheData();
    // Perform necessary operations and
    return // a boolean value
}
public IsCurrentUserAdmin(): Promise<boolean> {
    if (!this.isAdmin) {
        this.isAdmin = this.fetchIsAdmin();
    // You could also `await this.isAdmin` here, but that would result in waiting for every call
    return this.isAdmin;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An issue arises in VueJS when employing brackets and the replace function in Typescript

My journey with the Typescript language has just begun, and I am excited to dive deeper into it. Currently, I am working on a SPA-Wordpress project as a hobby using Vite (VueJS). However, I am facing some challenges with the syntax when transitioning from ...

How can I adjust the timeout or enhance my code for Excel Online's ExcelScript error regarding the Range getColumn function timing out?

I am struggling with a code that is supposed to scan through the "hello" sheet and remove any columns where the top cell contains the letter B: function main(workbook: ExcelScript.Workbook) { let ws = workbook.getWorksheet("hello"); let usedrange = ws ...

Function Type Mapping

I am in the process of creating a function type that is based on an existing utility type defining a mapping between keys and types: type TypeMap = { a: A; b: B; } The goal is to construct a multi-signature function type where the key is used as a ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

Using ngIf for various types of keys within a JavaScript array

concerts: [ { key: "field_concerts_time", lbl: "Date" }, { key: ["field_concert_fromtime", "field_concert_totime"], lbl: "Time", concat: "to" }, { key: "field_concerts_agereq", lbl: "Age R ...

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

Troubleshooting: React promise not functioning in functional component due to issues with UseEffect and UseState

I'm facing a challenge in fetching data and updating the state in a functional component using useEffect and useState. The issue arises when I try to separate the data fetching logic, which is done with axios async/await, into a different file for be ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'

I have been using ...

What is the most efficient way to find the sum of duplicates in an array based on two different properties and then return the

var data = [ { "amount": 270, "xlabel": "25-31/10", "datestatus": "past", "color": "#E74C3C", "y": 270, "date": "2020-10-31T00:00:00Z", "entityId": 1, "entityName": "Lenovo HK", "bankName": "BNP Paribas Bank", "b ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

Defining Array Types in TypeScript JSON

My attempt at coding a class in TypeScript has hit a roadblock. Whenever I try to utilize Jsons in an Array, the system crashes due to a TypeScript error. Here's the class I tried to create: class Api { url: string | undefined; credentials: Ar ...

transferring libraries via functions in TypeScript

As I work on developing my app, I have decided to implement the dependency-injection pattern. In passing mongoose and config libraries as parameters, I encountered an issue with the config library. Specifically, when hovering over config.get('dbUri&ap ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

What is the functionality of ngModel in the Angular Heroes Tour tutorial?

Hello everyone, this is my first post here. I have been diving into the Angular Tour of Heroes using Angular 6 and I think I understand how ngModel works, but there's one thing that puzzles me. How does it manage to update the data in my list when th ...

Merging an unspecified number of observables in Rxjs

My latest project involves creating a custom loader for @ngx-translate. The loader is designed to fetch multiple JSON translation files from a specific directory based on the chosen language. Currently, I am implementing file loading through an index.json ...

Is it possible to create a map of functions that preserves parameter types? How can variadic tuple types in TypeScript v4 potentially enhance this

Initially, I faced a challenge when trying to implement a function similar to mapDispatchToProps in Redux. I struggled with handling an array of functions (action creators) as arguments, but managed to come up with a workaround that works, although it feel ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...