Is it possible for a recursive function in expressjs to return an empty array?

I am working on extracting all child elements from MongoDB using a recursive function. The function loops through all the values and successfully logs them when pushed to an array. However, I am facing an issue where the returned array is empty. This code is being implemented in an Express.js environment. See the code snippet below:

static async getAllChildCat(categoryId){

    var allCat = [];

    let test = async (categoryId) => {
        let category = await NewCategory.find({ 'parent': categoryId });
        if (category.length > 0) {
            await category.forEach(async elem => {
                let newVal = await test(elem._id);
                console.log(elem);
                allCat.push(elem);
            });
        }
    }

    var val = await test(categoryId);

    return allCat;
}

Answer №1

experiment is a promise-based function, so it will result in an empty allCategories array. To ensure the return value is accurate, make sure to invoke it using await experiment(categoryId) to wait for the promise to be resolved.

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

extract the key identifier from the JSON reply

My JSON ResponseData example for form0 is provided below: { "MaterialType": "camera", "AssetID": 202773, "forms": [ { "release": "asyncCmd/accessCameraMulti", "action": "rest/Asset/202773/cameraAccessMultiple", ...

The issue of undefined req.user in NodeJS Express Passport

Testing authentication in a small app using express+passport without sessions. User must provide username and password for every action. After authorization (passport.authenticate()), request.user is undefined in the next middleware, even though passport&a ...

Looping through multiple JSON requests using $.getJSON without the use of the let statement to ensure cross

Currently, I am developing a web application that loads JSON files into leaflet layers based on user actions. The code snippet below successfully accomplishes this task when using the "let" statement. However, removing it results in variables from the last ...

Accessing Webpack bundles using an "@" symbol for imports

I am currently working on bundling a Node Express server that was created using TypeScript and is being packaged with Webpack. Everything seems to be running smoothly when I compile/transpile the code into one JavaScript file called server.js. However, af ...

You can only use RSA and DSA public keys during the babel-node installation process

I'm having difficulties with the installation process of babel-node npm i -g babel-node > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="53313231363f7e3d3c373613657d67d75716b70793f777b79">[email protected]< ...

What causes compatibility issues between JEST and import statements in NEXTJS?

Just starting out with unit testing in JavaScript and I'm attempting to create a unit test for a Next JS project. However, when running the test, I encountered the following error: Code: import {isBase64} from '../../service/base64-service&a ...

I implemented body parser in my code, but when I tried making a POST request using Postman with JSON data, it returned an

Within Controller/post.js: exports.createPost = (req,res)=>{ const post = new Post(req.body); console.log("Creating Post:", req.body); }; In my app.js file, I have body-parser installed: const bodyParser = require('body-parser'); app.use(body ...

Tips for positioning a picklist field dropdown on top of a lightning card in Lightning Web Components

Attempting to resolve an issue with CSS, I have tried adding the following code: .table-responsive, .dataTables_scrollBody { overflow: visible !important; } However, the solution did not work as expected. Interestingly, when applying a dropdown pickli ...

Enhance user interface dynamically with additional components in ReactJS by rendering them onClick. Master the optimal

Just started using React and I'm really enjoying it. I have a scenario where the parent component renders both: A TagBuilderContainer (which contains initially 1 TagBuilderComponent) An "Add Tag" button with an onClick event (intended to add a new ...

Submitting HTML forms in SilverStripe using Ajax

I need to transfer data from a basic HTML form to a controller using Ajax, then handle the data and send a response back. Currently, my setup looks like this: HomePage.ss <form method="POST" class="form-horizontal submit-form" onsubmit="return checkf ...

insert <asp:linkbutton> dynamically

I have a question regarding ASP: I am receiving a list of IDs from the server on my webpage. Can I display this list in a div below an ASP.NET control? div_containing_link += "" If not, is there another way to achieve this? For example, I want to displ ...

Improving React efficiency: What techniques can be used to prevent the entire component from re-rendering every time a prop changes?

Issue at Hand I created a custom component named PageLayoutSideBar.tsx that accepts two props: sideBar and content. This component is designed to make it easy to display the sideBar and page content with the appropriate styling and sidebar width. My conce ...

React : understanding the state concept as written like ...state

As I explore React, can you please explain the significance of this piece of code to me? const new_venues = this.state.venues.map((venue) => place_id === venue.place_id ? { ...venue, open : !venue.open } : { ...venue, open: false }); I understand the ...

The React date picker has limitations, as there are certain dates that users are unable

Recently, I came across an issue with a react date picker that I am using. Here is the code snippet: <DatePicker selected={selectedDate} onChange={handleDateChange} minDate={new Date()} className="form-control" /> In this image, when ...

What is the best way to link optional and undefined paths in AngularJS routing?

When it comes to AngularJS routing, I have a question. How can we combine the use of a star (*) to match paths with slashes and a question mark (?) to match optional paths? Specifically, I am looking to match both /admin/tasks and /admin/tasks/arbitrary/pa ...

Steps to indicate a cucumber test as incomplete using a callback function in a node environment

Can a cucumber test in Node be flagged as pending to prevent automated test failures while still specifying upcoming features? module.exports = function() { this.Given(/^Scenario for an upcoming feature$/, function(callback) { callback(); } ...

Error in Node.js: the function "myFunction" is not defined

Utilizing the fcm-node package to facilitate sending notifications from the Express API route to the app via a registration token. The function being used is as follows: const FCM = require('fcm-node'); const serverKey = ... const fcm = new FCM( ...

What is the best way to verify the existence of a remote image in AngularJS?

Here is an example of the code snippet : <div ng-repeat="u in users"> <!--An active URL will always be received --> <div ng-if="u.imageUrl"> <!--Check if the provided URL is active--> <!--Content only visible if image url is li ...

Guide to creating a custom wrapper for a Material UI component with React JS

I am utilizing the Material UI next library for my project and currently working with the List component. Due to the beta version of the library, some parameter names are subject to change. To prevent any future issues, I have decided to create a wrapper a ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...