The function is receiving an empty array of objects

This code is for an Ionic app written in typescript:

 let fileNames: any[] = [];
 fileNames = this.getFileNames("wildlife");
 console.log("file names:", fileNames);
 this.displayFiles(fileNames); 

The output shows a strange result, as even though there are 50 items present, it displays Array(0). The issue arises when passing the array to a function:

 displayFiles( files) 
    {
     files.forEach(item => {
    console.log(item) <- item does not exist

    });
    }

The array turns out to be empty. Why is that happening? Is there another way to pass the array and iterate through its objects?

EDIT:

getFileNames(folder) {
    let fileNames: any[] = [];

    this.file.listDir(this.file.applicationDirectory, 'www/assets/' + folder)
      .then((items) => {
        // console.log(items);

        items.forEach(item => {
          fileNames.push({
            fileName: item.name,
            name: this.getName( item.name)
          });
        });
      })
      .catch(err =>
        console.log("error: ", err));

    return fileNames;
  }

Answer №1

Make sure to invoke your retrieveDocuments function as an asynchronous operation.

let documents: any[] = [];
 this.retrieveDocuments("nature")
   .then(data => {
     documents = data;
     console.log("documents:", documents);
     this.display(documents);
 }); 

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

Comparison between referencing the DOM and storing references to the DOM elements

Can you explain the contrast between these two statements? $("#txt").val("123"); versus var txt=$("#txt"); txt.val("123"); Which statement is considered more effective in terms of efficiency? ...

Issue with Mockjax: asynchronous form submissions are not being intercepted

Currently, I am facing an issue while using qUnit and mockjax to handle a basic async form submission. It seems like the async POST request is passing through mockjax for some reason. test 'RuleModal closes the modal on a successful form submission e ...

Information not displaying correctly on the screen

My latest project is a recipe app called Forkify where I am utilizing JavaScript, npm, Babel, Webpack, and a custom API for data retrieval. API URL Search Example Get Example The app displays recipes with their required ingredients on the screen. Addit ...

Troubleshooting: Issue with jQuery not retrieving the value of input:nth-child(n)

My goal is to dynamically change the price when the model number changes, requiring the id number and quantity to calculate it accurately. Here is the HTML code I have: <div class="col-sm-9 topnav"> <span> ...

Handling AJAX requests in ASP.NET for efficient communication

I'm in the process of setting up ajax communication between a JavaScript frontend and an ASP.NET backend. While researching, I came across this sample code on w3schools: function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatecha ...

Verify that two variables within a multidimensional array are identical within the array

I'm working with a complex multidimensional array structured like this: array(4) { [0]=> array(3) { ["rowid"]=> int(3) ["columnid"]=> int(5) ["seattype"]=> int(10) } [1]=> ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

Using JLinq for Date-Based Filtering of JSON Data

I have been trying to use JLinq for filtering JSON data, but I am facing an issue with filtering by date. Despite attempting different methods, the problem persists. Below is a snippet of my code: //This works jlinq.from(myData) .select(function ...

Invoke an Angular service from a separate JavaScript file

I have a few javascript and html files: User.js, index.html, Door.js I am looking to utilize a function in the User.js file. Link to my user.js file Link to my door.js file I am trying to call the getUserInfo function from User.Js within the Door.j ...

Alternatives to the PHP Foreach Tree Approach

I often find myself using nested foreach loops when parsing JSON data in my workflows, but I can't shake the feeling that there must be a more efficient solution out there. I've come across mentions of array_walk as a possible alternative, but I& ...

How can a secondary property type be determined by the key utilized in another property?

My goal is to develop a filter type that uses the primary object type to specify a set of keys for "field" and then assigns the appropriate type to the "value". However, I have encountered challenges in achieving this as the best outcome I could attain w ...

Effective ways to transmit a variable array from an HTML document to a PHP server

Is there a better method for transferring a variable array from HTML to PHP? I attempted to use the serialize function, but it doesn't seem to be functioning correctly. Any suggestions would be greatly appreciated. //HTML var arrayTextAreasNames = [ ...

Having difficulty deciphering the legend in the Highcharts library for Angular (angular-highcharts)

I have a requirement to display two datasets as dual column charts. (2) [{…}, {…}] 0: historyDate: "2021-02-10T10:00:000Z" documentStatusHistory: CANCELLED: 6 COMPLETED: 52 IN_PROGRESS: 1 OPEN: 1 ...

Mastering unit testing with Behaviour Subjects in Angular

I am looking to test the get and set methods of my user.store.ts file. The get() method is used to retrieve users, while addUsers() is utilized to add new Users to the BehaviorSubject. How can I accomplish this? import { Injectable } from '@angular/c ...

Bug causing connection issues in Node.js when dealing with IP redirection

I recently encountered an issue with NodeJS while using a kafka node on a node-red instance installed on my RPI3. Let me paint you the scenario: I have a cluster set up with a functioning Kafka instance. The machine hosting the Kafka broker has a private ...

What's the best way to decrypt a string in NodeJS?

In the midst of my NodeJS & MongoDB project, I've encountered a requirement to encrypt the content of articles before they are published. The catch is that the encrypted content should only be displayed if the correct key-codes are entered. For ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

Using Scanf in C to Handle Multiple Conditions

TLDR: Checking if scanned input into an array is an integer while using EOF. I am trying to scan numbers into an array until EOF using statically allocated memory. I am still a beginner and dynamically allocated memory is difficult for me to grasp at the ...

I seem to be stuck in an endless cycle with React hooks and I can't figure out the root cause

Explore the example here: https://codesandbox.io/s/wandering-wildflower-764w4 Essentially, my goal is to achieve the following: In the provided example, I have a server validation function that has been mocked. My objective is to maintain the state local ...

How can you achieve three layers of nested quotes in Dynamic HTML?

Working on an app that utilizes JQuery and JQTouch for iOS. The issue I'm facing involves dynamically generated HTML lists where the user clicks a row that needs to be highlighted. However, achieving this has proven tricky due to nesting 3 sets of quo ...