What could be causing the empty object return from the Async function in my Typescript code on Next JS?

Encountering issues with an async function.

In the ../lib folder, I have a class for handling data from an API website. However, when attempting to load the API data within an async function, I encounter difficulties.

The async function does not return anything - even when creating and trying to return an object within the async function.

Instead, I consistently receive an empty object {} whenever the function is called.

Below is the code snippet:

 private procurr(obj){
    // Processing begins here
    const mainObj = async function(ob) {
        var robj : any = [];
        var item = {};
        var i : number = 0;
        var total : number = 10;
        try{
            for(item in ob){
                let res2 = await axios.get('https://hacker-news.firebaseio.com/v0/item/'+item+'.json');
                const obji = await res2.data;
                var word : string = this.help.mode(this.help.words(obji.title));
                if(word.length > 0){
                    if(i < total){
                        robj[i] = (this.help.inArr(word, robj)) ? this.help.incScore(robj[i]) : {'word': word, 'score':1};
                        // increment
                        i++;
                    }
                }
            }
        }catch(error){
            console.error(error);
        }
        
        // return JSON.parse(robj);
        return ob;       
    }

    // exports.mainObj = mainObj;
    // Return statement
    // return obj;
    return mainObj(obj);
}

EDITED:

I am calling the procurr(obj) method from q1(obj) as follows:

      // Creating the question method
     public q1(obj) : any {
       var last25 = this.help.last25(obj);
       // Returning
       return this.procurr(last25);
     }

Calling the q1(obj) method from getStaticProps():

     export async function getStaticProps() {
        const postClass = new Posts();
        // Fetching data
        const res = await axios.get('https://hacker- 
        news.firebaseio.com/v0/topstories.json');
        const obj = await res.data;

        const ob = JSON.stringify(postClass.q1(obj));

        return {
          props: { ob }
        }
    }

The API call returns an object containing post IDs from Hacker News website.

Answer №1

If you have a series of asynchronous methods and forget to include the await keyword at the end, attempting to use JSON.stringify on a Promise will result in an empty object being returned.

const p = new Promise(resolve => resolve({foo:"bar"}));

console.log(JSON.stringify(p)) // Instead of {foo:"bar"}, you will get an empty object

Since the method from which you are calling it is already marked as async, simply remember to add the await keyword:

const ob = JSON.stringify(await postClass.q1(obj));

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

Could you confirm if this is a TypeScript function?

Recently, while delving into the vue-next source code, I stumbled upon a particular line that left me puzzled. Due to my limited experience with TypeScript, I found myself struggling to grasp its purpose. Could someone clarify if this snippet constitutes ...

What is the most efficient and hygienic method for storing text content in JavaScript/DOM?

Typically, I encounter version 1 in most cases. However, some of the open source projects I am involved with utilize version 2, and I have also utilized version 3 previously. Does anyone have a more sophisticated solution that is possibly more scalable? V ...

Maintain the previous droppable positioning after refreshing the page

I am encountering an issue with the .droppable event. I have set up two sections where I can move elements, but every time the page is refreshed, the positioning of the elements reverts to the initial position. How can I maintain the last positioning of th ...

Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something? I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive: angular.js:12701 POST 500 (Internal Server Error ...

What is the process for adjusting the width of an element using JavaScript?

I have a unique bar with one half red and the other green. I am trying to subtract 1vw from the width of the red section. Unfortunately, using style.width is not yielding the desired result. See below for the code snippet I am currently using: //FIGHT do ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

What could be preventing my CSV file from being saved empty?

I am currently working on a function that processes the results of a web scraping operation I conducted on an online t-shirt store. Every t-shirt is represented as an object, featuring attributes such as title, price, imgUrl, URL, and time. These objects ...

Is there a solution to resolve the Firestore issue stating: "FieldPath.documentId is not a recognized function"?

In my function, I am retrieving data from two collections in Firestore: Media and Users. Inside the Users collection, there is a subcollection containing a list of all the user's movies. The Media collection includes details about each movie. My goal ...

Encountering a NextJs compilation error when using next-pwa's web loader

Although my NextJS application is running smoothly, I wanted to take it up a notch by converting it into a PWA. I've already installed the Next-pwa package and built the application, but unfortunately, I encountered an error in the browser. Here&apo ...

The semantic-ui-react searchable dropdown feature may not show all of the options from the API right away

For some reason, when I attempt to call an API in order to populate the options for semantic UI, only a portion of the options are displayed initially. To view the full list, I have to first click outside the dropdown (blur it) and then click inside it aga ...

What is the best way to retrieve a FireStore document ID from an object?

I'm in the process of trying to reference an auto-generated firestore document ID in order to create a subcollection within it. The issue I'm facing is that although I can locate the document ID, I'm struggling to save it to a variable in a ...

Incorporate a div beside a button using componentDidMount in a React component

Upon page load, I aim to position an info icon div next to a button node. However, the button node is not available when componentDidMount is triggered. I have attempted to use setTimeout, but its effectiveness varies depending on the amount of data in th ...

Incorporating a YouTube channel into mobile websites

While it's relatively easy to embed single YouTube videos in mobile pages with the help of Google, I'm still struggling with embedding a whole channel. The issue seems to revolve around the screen width, and my attempts at using JavaScript have n ...

Using Html to differentiate input based on type

Looking for input on the code snippet below: <table class="details-table" *ngIf="animal && animaldata"> <tr *ngFor="let attribute of animaldata.Attributes"> <td class="details-property">{{ attribute.AttributeLabel }}& ...

Sending a file to the jqGrid handler

Currently, I am using Grails in combination with jqGrid and attempting to implement a rather unique feature. My goal is to allow users to upload a file which will then be sent to the jqGrid controller and used as a filter for the data displayed on the grid ...

How can I validate HTML input elements within a DIV (a visible wizard step) situated within a FORM?

I recently made a decision to develop a wizard form using HTML 5 (specifically ASP.NET MVC). Below is the structure of my HTML form: @using (Html.BeginForm()) { <div class="wizard-step"> <input type="text" name="firstname" placeholder ...

What is the best way to determine the file size using Node.js?

My current challenge involves using multer for uploading images and documents with a restriction on file size, specifically limiting uploads to files under 2MB. I have attempted to find the size of the file or document using the code below, but it is not p ...

implementing ajax form submission in codeigniter

After submitting my form, validation is checked in the JavaScript file, and then the kickerLogin() function is called. I receive an alert message of datastring. However, the data is not sent to the specified URL in the AJAX request, but the form still ge ...

Having trouble sending a JSON object from Typescript to a Web API endpoint via POST request

When attempting to pass a JSON Object from a TypeScript POST call to a Web API method, I have encountered an issue. Fiddler indicates that the object has been successfully converted into JSON with the Content-Type set as 'application/JSON'. Howev ...

Tips on obtaining the response (in JSON format) in your console when accessing a URL

Can someone help me integrate this code into my project and guide me on how to proceed with it? function validate() { var un = document.loginscreen.uname.value; var pw = document.loginscreen.psw.value; var username = "John_Smith"; var passw ...