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

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

Please convert the code to async/await format and modify the output structure as specified

const getWorkoutPlan = async (plan) => { let workoutPlan = {}; for (let day in plan) { workoutPlan[day] = await Promise.all( Object.keys(plan[day]).map(async (muscle) => { const query = format("select * from %I where id in (%L) ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

Replicating an array of typed objects in Angular2

I have a collection of specific object types and I'm looking to duplicate it so that I can work on a separate version. In order for the configuratorProduct to function correctly, I need to provide it with a copy of the listProducts values: listPro ...

What is the best way to retrieve an accurately matched array?

I am working on a function that analyzes a string of DNA and should return an accurately matched DNA array. Here is the code snippet I have experimented with: function checkDNA(dna) { var dnaarr = []; for(var i = 0; i < dna.length; i++) { ...

One way to incorporate type annotations into your onChange and onClick functions in TypeScript when working with React is by specifying the expected

Recently, I created a component type Properties = { label: string, autoFocus: boolean, onClick: (e: React.ClickEvent<HTMLInputElement>) => void, onChange: (e: React.ChangeEvent<HTMLInputElement>) => void } const InputField = ({ h ...

The call to react.cloneElement does not match any overloads

I'm encountering a typescript error in my React code when using React.cloneElement with the first parameter "children", and I am unsure of how to resolve it. As a newcomer to typescript, I believe that the type definitions in index.d.ts for cloneElem ...

What sets apart the two methods of defining an event in a React component?

Can you explain the nuances between these two approaches to declaring events in a React component? Is it merely a matter of personal preference, or are there more subtle distinctions between them? interface PropsX { onClick: () => void; } const But ...

Issue with NgFor nested component not refreshing after @Input modification

When populating a component called ContactUpdatableItem within a NgFor, the code looks like this: <section class="plContactCreation-listItem" *ngFor="let contact of contacts$ | async; index as idx" > <contact-updatable-item [c ...

Angular rxjs Distinctions

Coming from AngularJS to Angular, I'm still trying to wrap my head around rxjs observable. For example: User.ts export class User { id?:any; username:string; password:string; } Using <User[]> myUser(header: any) { const url = `${this.mainUr ...

Unable to locate the type definition file for 'jquery'

After updating my NuGet packages, I encountered an issue where I can no longer compile due to an error related to the bootstrap definition file not being able to find the jquery definition file within my project. Prior to the update, the directory structu ...

ngx-emoji mart - The error message "Type 'string' is not assignable" is being displayed

While working on a project involving the @ctrl/ngx-emoji-mart package, I encountered a perplexing issue. The code functioned flawlessly in Stackblitz but when I attempted to run it on my local system, an error surfaced: Type 'string' is not assig ...

Migration of old AngularJS to TypeScript in require.js does not recognize import statements

I am looking to transition my aging AngularJS application from JavaScript to TypeScript. To load the necessary components, I am currently utilizing require.js. In order to maintain compatibility with scripts that do not use require.js, I have opted for usi ...

How can I pass DOCUMENT in Angular?

In my directive, I use dependency injection to access the DOCUMENT and set up an event listener: constructor(@Inject(DOCUMENT) private document: Document) {} ngOnInit() { this.document.addEventListener('click', this.clicked, true); } @Bound ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Angular error: Trying to access the sort property of an undefined value

I am currently working on creating a sorting function and pipe for a table. I found guidance on how to do this by following a tutorial at this link, and here is the plunker example. In the example, the table header should be clickable to trigger the sort() ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Remember to always call "done()" in Typescript + Mocha/Chai when dealing with async tests and hooks. Additionally, when returning a Promise, make sure it resolves correctly

It seems like I'm facing an old issue that I just can't seem to resolve, despite trying everything in my power. The error message reads: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Pro ...