What is the best way to store the output of a function in a local variable?

In my Type Script code, I am looking to store the return value of a function in a local variable. The process is outlined below:

getdetail1(store){              
    let Cust_id=this.sharedata.latus_lead.m_type
    let url="http:domain.com"
    console.log(url);
    let res;
    this.loginservice.leaddata = null;
    this.loginservice.getdetails(url).then(data=>{
        let lead=data;
        this.details=lead[0];
        res=lead[0];                          
    });
    return res;
}

To call the function, follow these steps:

let res = this.getdetail1(store);

The following snippet showcases the login service code utilized:

getdetails(query){
       if (this.leaddata) {
        // already loaded data  
        console.log("already data loaded lead") ;
        return Promise.resolve(this.leaddata);
      }
    // don't have the data yet
    return new Promise(resolve => {
      // We're using Angular HTTP provider to request the data,
      // then on the response, it'll map the JSON data to a parsed JS object.
      // Next, we process the data and resolve the promise with the new data.
        this.http.get(query)
        .map(res => res.json())
        .subscribe(data => {
          // we've got back the raw data, now generate the core schedule data
          // and save the data for later reference
          this.leaddata = data;
          resolve(this.leaddata);
        });
    });

  }

This section covers how promises are handled within the code.

Answer №1

To ensure proper handling of asynchronous operations in your code, it is recommended to return a promise instead of a variable. Modify your code like this:

getDetail(store){              
    let customerId = this.sharedData.customers.id;
    let url = "http:example.com";
    console.log(url);
    let result;
    this.loginService.customerData = null;

    return this.loginService.fetchDetails(url);
}

Then, invoke the function like this:

this.getDetail(store)
    .then((response) => {
        let result = response;
        console.log("Here is your data: ", result);
    })
    .catch((error) => {
        console.log("An error occurred: ", error);
    });

Answer №2

To solve this issue, you should utilize promise chaining. For more information, refer to this link.

Consider the following implementation:

getDetail(store){              
    let customerID = this.sharedData.customer.id;
    let url = "http://example.com";
    console.log(url);
    this.loginService.leadData = null;
    
    return this.loginService.getDetails(url).then(data => {
        let lead = data;
        this.details = lead[0];
        return lead[0];                          
    }); // Returning both the promise call and the data

Then use the following method:

this.getDetail1(store).then(data => this.response = data;)

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

How to eliminate all special characters from a text in Angular

Suppose I receive a string containing special characters that needs to be transformed using filter/pipe, with the additional requirement of capitalizing the first letter of each word. For instance, transforming "@!₪ test stri&!ng₪" into "Test Stri ...

Typescript in React is throwing an error that says you cannot destructure the property 'colored' from the 'boxShadows' object because it is undefined

After downloading the material dashboard react theme from an open source GitHub project, I tried to convert the project into Typescript (React + Typescript). However, I encountered the following error (See Attached Image) https://i.stack.imgur.com/YZKpK.p ...

The timestamp will display a different date and time on the local system if it is generated using Go on AWS

My angular application is connected to a REST API built with golang. I have implemented a todo list feature where users can create todos for weekly or monthly tasks. When creating a todo, I use JavaScript to generate the first timestamp and submit it to th ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

Issues with include and exclude directives in tsconfig.json are causing problems

I am currently working on a web project that involves organizing folders. Within my project structure, I have subfolders like the following: src/app/shared/models src/app/shared/services src/app/shared/types Each of these subfolders contains additional ...

Tips for making a dynamic link button using Angular

I am currently working on creating responsive buttons that will navigate to specific pages using Angular routing. Here is my routing configuration: const routes: Routes = [ { path: 'home', component: HomeComponent}, { path: ' ...

Tips for incorporating child components when creating unit tests in Angular 2

While working on my component, I encountered an issue with the child component during unit testing. An error message is appearing stating that the child component is not defined. Any advice or solutions would be greatly appreciated. Thank you in advance. ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...

How can I set up TypeScript warnings in Visual Studio Code to display as errors?

Take this scenario for instance async function a() { await null; } In VS Code, there is a minor warning about using await: 'await' has no effect on the type of this expression. ts(80007) Is there a way to elevate that warning to an error in b ...

Tips for accessing Firebase document fields with Angular Firestore (version 7)

My current task involves retrieving a Firebase document property based on the specified model: After successfully locating a document with this code snippet: //Users - collection name, uid - document uid. I am attempting to access the isAdmin property u ...

Route user based on login status using router

I want to set up automatic routing to a login page for users who are not logged in. app.module.ts import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from &ap ...

Angular's ngClass directive failed to be applied correctly

I am currently experimenting with the use of [ngClass] in Angular and it appears that it is not being applied as expected. Interestingly, [ngStyle] for similar CSS styles is working without any issues. What could I be doing wrong in this scenario? There ar ...

Dialog in Angular Material refuses to close even after calling the dialog.close() function

I've been struggling with this issue for a while, hoping someone can assist. In my Angular project, I have a login component with a dialog that opens a new popup window. Upon successful login, this window closes and triggers the following function: l ...

There is no XHR request sent when invoking the http function

I am facing challenges in configuring a service in angular2 to interact with a REST backend. My attempt at setting up a basic example for sending requests to a rest backend and handling the response seems to be on track. The Service is being called correc ...

Typescript fails to identify the parameter type of callbacks

I am facing a challenge with the function below and its callback type: type Callbacks = { onSuccess: (a: string) => void; }; function myFunction(event: string, ...args: [...any, Callbacks]) { } The function works correctly except for one issue - ...

Angular causing alignment issues for items not centered

I'm having trouble centering the contents of a div with my code. The properties I am applying don't seem to work. Any idea why this is happening? <div class='center'> <form (ngSubmit)="loginUser()" style="background: steel ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Can a type be established that references a type parameter from a different line?

Exploring the Promise type with an illustration: interface Promise<T> { then<TResult1 = T, TResult2 = never>( onfulfilled?: | ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ...