Best practice for managing asynchronous calls and returns in TypeScript

I’ve recently started working on an Ionic 4 project, delving into the realms of Javascript / Typescript for the first time. Understanding async / await / promise seems to be a bit challenging for me.

Here’s the scenario:

In one of the pages of my app (let’s refer to it as tab1.page.ts ), there's a function that calls a service function:

Get_Sim_Agents() {
       this.simConfig.Get_Sim_Agents();
    }

Now, in the service page, here’s the function (a basic http get function):

/**
     * Fetch the datas in order to populate the app
     */
    Get_Sim_Agents(){

        this.http.get(
            "http://" +
            this.ip_address +
            ":" +
            this.port +
            "/get_datas"
        ).subscribe(response => {

            var data = JSON.stringify(response, null, 2);

            try {
                var obj = JSON.parse(data);
                // Here I manipulate the retrieved data
                });

            } catch (e) {
                console.log(e);
            }
        });
    }

Currently, everything works just fine. However, I wish for the service function to return the treated data as a string. But figuring out the correct syntax has been quite a challenge for me. Here’s what I’ve attempted:

In the service:

/**
     * Fetch the Sim_Agents from the Simulation_orchestrator in order to populate the app
     */
    async Get_Sim_Agents() : Promise<string>{

        this.http.get(
            "http://" +
            this.simulation_orchestrator_ip_address +
            ":" +
            this.simulation_orchestrator_port +
            "/get_sim_agents"
        ).subscribe(response => {

            var data = JSON.stringify(response, null, 2);

            // Perform some actions on the data

            return JSON.parse(data);
            });

        return 'test';
    }

And on the page:

Get_Sim_Agents() {
        this.simConfig.Get_Sim_Agents().then((result) => {console.log(result)});
    }

With this code snippet, my function called on the page immediately returns ‘test’. What I actually desire is for it to wait until the http response is received. I’ve tried various syntaxes but haven’t been able to achieve the desired outcome 🤔

Just to make things clear:

What I’m aiming for is:

1/ The page triggers the service function 2/ The service sends the request and receives a response 3/ The service performs necessary operations (like populating the app with the data) 4/ Subsequently, it returns a string back to the page, saying “job is done”

But so far, all I’ve found are solutions that directly send the response from the service to the page without any pre-treatment by the service

Answer №1

Your current approach is ineffective because the method Get_Sim_Agents does not return a promise, but instead returns a string. Although asynchronous calls are made within this method, the final output is still a string.

To resolve this issue, consider implementing the following:

/**
     * Fetch the Sim_Agents from the Simulation_orchestrator in order to populate the app
     */
    async Get_Sim_Agents() : Promise<string>{

        return this.http.get(
            "http://" +
            this.simulation_orchestrator_ip_address +
            ":" +
            this.simulation_orchestrator_port +
            "/get_sim_agents"
        ).toPromise().then(response => {

            var data = JSON.stringify(response, null, 2);

            // Perform required operations on the data

            return JSON.parse(data);
        });
    }

Note that the functionality of toPromise may vary depending on the version of RxJS being used.

Additionally, it is worth questioning why you are converting the response to a string and then parsing it back into JSON.

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

Locate and extract the JSON object using the specified key-value pair

Trying to extract a specific object from a complex json file, noting the key, and then returning a new json poses a challenge. I am using expressjs as the backend for this task. Sample.json '[{"ServID":"Rai 1","Parametri" ...

Sending an array of strings to the function is not allowed

I'm encountering an issue with the following function: function proc(unames: Array<string>){} When I attempt to pass the function the following input: import _ = require('lodash'); const usernames = _.flattenDeep([unames]).filt ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

Optimal techniques for leveraging CSS within Mui and Reactjs

Just starting out with mui, I'm currently working on styling CSS for mui components like so <Typography variant="h5" sx={{ fontWeight: "bold", color: "#1a759f", display: "flex", ...

custom vertical tab label text not aligning to the right in material-ui with textAlign

I am struggling with customizing the tabs in material-ui to display them vertically. I also want the text labels of these tabs to align to the right for a more cohesive look. Despite trying various styling options, I have not been successful in achieving t ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

Iterate through an array index within a map function in a ReactJS component

I am working with a map that contains images of metros, and I need to increment the number by 1 at each loop iteration. For example, the first loop will display {metrosImages[0]}, then {metrosImages[1]}, and so on until the loop reaches its end. The code ...

Steps for redirecting from a URL containing location.hash to a different page

Recently, I decided to move a section of one of my webpages from dummy.com/get-started/#setup to its own page at dummy.com/setup. After making this change, I went ahead and deleted the old /get-started page on my website. Many people have bookmarks saved ...

Webpack bundling only a singular Typescript file rather than all of its dependencies

I'm currently facing a challenge while attempting to consolidate all the files in my Typescript project, along with their dependencies from node_modules, into a single file using Webpack. Despite trying multiple options, it seems that only the entry f ...

Encountered an issue during installation: Error message states that Typings command was not

I've encountered permission errors with npm, so I decided to reinstall it. However, I'm facing an issue with the 'typings' part where it displays a 'typings: command not found' error. This problem seems to be related to Angula ...

The redirection from Azure AD SSO is not working properly following a logout

In my quest to integrate Azure AD login into a single-page application built with ReactJS, I utilized the MSAL React package. While successfully implementing the login functionality, I encountered an issue during logout where I found myself unable to redir ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Sending a JSONP request to a PHP script

For my application submission, I am trying to send a JSON object to a PHP script that will return a JSON response. The challenge here is that the domain does not comply with the same-origin policy, meaning the JSON is being sent from a different domain. Up ...

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

Utilizing AngularJS to Retrieve Row Information Upon Button Selection

I'm currently developing an application that includes a feature allowing users to run a query from a drop-down menu and view the data in a table. Each row in the table will have a button, and when clicked, I need to capture the values of that specific ...

Unable to use href attribute as intended

HTML: <a id="Switch">Click here to switch</a> <a href="image1_large.png" class="mainA blade"> <img id="mainImage" src="image1.png"/></a> Javascript: <script> $(function() { $('#Switch').click(functio ...

Utilize the cube function in JavaScript to zoom in on the cube automatically when the page loads

I have the code below. When the page loads, I would like the cube to zoom out and stop. I am new to 3js and have no idea how to achieve this. I want the cube to start small and then grow into a larger cube before stopping. <script> //var re ...