DEV Community

chikyabad
chikyabad

Posted on

Recursive Function

Hi experts,

I have the below recursive logic:

// Imports
const cds = require("@sap/cds");

/**
  * The service implementation with all service handlers
  */
module.exports = cds.service.impl(async function () {

    const { locations} = this.entities();

    this.on("locationTree", async (req) => {

      const location = await SELECT.one.from(locations).where({ location: req.data.location})

      let locationTree = []

      await buildTree(location,locationTree)

      console.log(locationTree)

      return locationTree

    } )

    async function buildTree(location, tree) {

      await tree.push(location)

      const childLocations = await SELECT.from(locations).where({ parentLocation: location.location})

      if (childLocations) {
        childLocations.forEach(async (child) => {
          await buildTree(child,tree)
        });
      } else {
        return
      }

    }

});
Enter fullscreen mode Exit fullscreen mode

Image description

Printing the final locationTree variable on the log I can see the below:

locationtree.png

Here I can see inside the array the 9 expected entries that matches the length 9 but only the first 3 objects are replied in the response which matches with the (3) at the top of the figure above.

Any idea what is going on?

Thanks!

C.

Top comments (0)