TypeScript: empty JSON response

I am encountering an issue with the JSON data being blank in the code below.

The class is defined as follows:

export class Account {

public amount: string;
public name: string;

constructor(amount: string, name: string) {
    this.amount = amount;
    this.name= name;

   }
}

let account: Account[] =[];

function accountList () {
    client.getAccounts({}, function (err, accounts) {
        accounts.forEach(function (acct) {
            console.log('my balance: ' + acct.balance.amount + ' for ' + acct.name);
            account.push(new Account(acct.balance.amount, acct.name));
        });
        return account;
    })
};

The function is called using the following:

app.get('/accounts', (req, res) =>
    res.send(JSON.stringify(accountList())));

Please advise on any errors present in the code above.

Answer №1

Your issue is discussed in the comments below (hopefully). It's a common problem, but can be difficult to explain.

function retrieveAccounts () {
    // (1) Fetch accounts asynchronously; function `function (err, accounts)` will be triggered
    client.getAccounts({}, function (err, accounts) {
        // (3) Once the async call is complete, this inner function is executed
        // However, retrieveAccounts has already returned void - see (2) below
        accounts.forEach(function (acct) {
            console.log('Account balance: ' + acct.balance.amount + ' for ' + acct.name);
            account.push(new Account(acct.balance.amount, acct.name));
        });
        return account;
    })

    // (2) The retrieveAccounts method returns
};

You can address this by passing a callback into retrieveAccounts - which you invoke instead of return account; OR you could return a Promise from retrieveAccounts and handle JSON serialization in the then.

Promise Approach

Here's an example utilizing a promise:

function retrieveAccounts(): Promise<Account[]> {
    return new Promise((resolve, reject) => {
        client.getAccounts({}, function (err, accounts) {
            let account: Account[] = [];

            accounts.forEach(function (acct) {
                console.log('Account balance: ' + acct.balance.amount + ' for ' + acct.name);
                account.push(new Account(acct.balance.amount, acct.name));
            });

            resolve(account);
        });
    });
}

And your calling code:

app.get('/accounts', (req, res) => {
    retrieveAccounts().then((accounts) => {
        res.send(JSON.stringify(accounts));
    });
});

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

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Enhance Material UI with custom properties

Is it possible to add custom props to a Material UI component? I am looking to include additional props beyond what is provided by the API for a specific component. For example, when using Link: https://material-ui.com/api/link/ According to the document ...

What are the consequences of not subscribing to an HttpClient request that returns observables in an Angular application?

Exploring Angular and TypeScript, I am currently delving into the concepts of HttpClient, observables, and subscribe. When I include the following code in a component function: console.log(this.http.get('assets/user.json')); I receive an objec ...

Error: The specified updateTag type in the Angular SEO service is not compatible

I am in the process of developing an SEO service using Angular's Meta service (https://angular.io/api/platform-browser/Meta) Within the service, there is a method for managing social media tags that seems to be encountering issues and producing the f ...

Angular 2 is having trouble identifying a component that was imported from a module

Exploring the functionalities of Angular2, I am attempting to have one module (BreadcrumbDemoModule) import the component from another module (BreadcrumbModule). At the moment, the BreadcrumbModule consists of only one component: ng2-breadcrumb. However, ...

Ways of modifying the readonly and required attributes of an HTML element using Angular2 Typescript

I am facing an issue with changing input field attributes back and forth in some of my components. I have a code that successfully changes the readonly attribute as needed. However, when trying to change the required attribute, Angular2 still considers the ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

Show the values in the second dropdown menu according to the selection made in the first dropdown menu using Angular 8

My goal is to retrieve data and populate two dropdowns based on user selection. However, the code I've written isn't giving me the desired output and instead, errors are occurring. Being new to Angular, I would appreciate a review of my code. Her ...

Having trouble with enzyme in React Typescript application

One of my components is called app.tsx import React, { useState } from "react"; const TestComponent = () => { return( <> <div className="head">hey there</div> <select name="xyz" id=&qu ...

What is the process for creating accurate types for my package?

Currently, I am in the process of creating an npm package to be used by other developers within my company. While most aspects are functioning smoothly, I am facing challenges with getting the declarations right. I have experimented with various methods f ...

How to pass a String Array to a String literal in JavaScript

I need to pass an array of string values to a string literal in the following way Code : var arr = ['1','2556','3','4','5']; ... ... var output = ` <scr`+`ipt> window.stringArray = [`+ arr +`] & ...

Determine the data type of a class property by referencing the data type of a different property within the

Why am I getting an error when assigning to this.propertyB in TypeScript? class Example { public readonly propertyA: boolean; private readonly propertyB: this['propertyA'] extends true ? null : 'value'; public constructor() ...

Generating instances using TypeScript generics

Looking to create a factory for instantiating classes with generics. After checking out the TypeScript docs, everything seems to work as expected. Here's a simplified version of how it can be done: class Person { firstName = 'John'; ...

Function that wraps JSX elements with the ability to infer types through generics

At the moment, this function is functioning properly function wrapElement(elem: JSX.Element) { return ({ ...props }) => React.cloneElement(elem, { ...props }) } I've been using it in this way to benefit from intelliSense for tailwind classes con ...

The error property is not found in the type AxiosResponse<any, any> or { error: AxiosError<unknown, any>; }

As a beginner with typescript, I am encountering some issues with the following code snippet import axios, { AxiosResponse, AxiosError } from 'axios'; const get = async () => { const url = 'https://example.com'; const reques ...

Setting up a React state with an Object using Typescript: A step-by-step guide

As someone who is new to TypeScript, I have a solid understanding of how to set up an interface for certain types. However, I am struggling to comprehend how the same concept would apply to an Object type. interface MyProps { defaultgreeting: 'He ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

Incorporate a fresh element into an object after its initial creation

Hello, I am looking to create an object in JavaScript that includes an array-object field called "Cities." Within each city entry, there should be information such as the city's name, ID, key, and a District array object containing town data for that ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...