The for loop effectively populates the array with elements, but strangely returns an empty array afterwards

After spending all morning troubleshooting, I finally got this code to run successfully and add elements to the array. However, a perplexing issue arises when I try to return the array as it comes back empty. It's been a frustrating morning of debugging for me.

details.getDetails = function(idSet, pageNum) {
      var page = idSet[pageNum],
          placeDetails = [],
          i;

      for(i=0; i<page.length; i++){
        ngGPlacesAPI.placeDetails({placeId: page[i]})
          .then(function(data){
            response = data;
            placeDetails.push(response);
            console.log(placeDetails) //This shows the loop running and the array being populated
          })
      }
      return placeDetails;
      console.log(placeDetails) //This returns empty array 
    };

I suspected that the issue might be related to asynchronous data handling, as Rayon mentioned. I attempted to implement a promise-based solution but I'm unsure if I've done it correctly. Here is the modified code snippet:

.factory('details', function(ngGPlacesAPI, $q){
    var response,
        details = {};

 details.getDetails = function(idSet, pageNum) {
      var page = idSet[pageNum],
          deferred = $q.defer,
          placeDetails = [],
          i;

      for(i=0; i<page.length; i++){
        ngGPlacesAPI.placeDetails({placeId: page[i]})
          .then(function(data){
            response = data;
            placeDetails.push(response);
          })
      }
      deferred.resolve(placeDetails);
      console.log(deferred.promise);
      return deferred.promise;
    };

    // Return Details Object
    return details;
  });

Answer №1

The issue at hand arises from the fact that the .placeDetails function executes immediately, causing the for loop to finish before any data is retrieved. Therefore, utilizing a Promise in this scenario may not be beneficial as the resolve call will occur almost instantly.

One potential solution is to explore using $q.all to ensure that all calls to placeDetails are completed before resolving the promise.

You can try implementing something similar to the code below (not tested). While it may require adjustments, it should provide you with a basic understanding of the approach:

details.getDetails = function(idSet, pageNum) {
      var page = idSet[pageNum],
          placeDetails = [],
          mainDeferred = $q.defer(),
          promises = [];

      for(var i=0; i<page.length; i++){
        var deferred = $q.defer();
        ngGPlacesAPI.placeDetails({placeId: page[i]})
          .then(function(data){
            placeDetails.push(data);
            deferred.resolve();
          });
        promises.push(deferred.promise);
      }
    $q.all(promises).then(function() {
       mainDeferred.resolve(placeDetails); 
    });
    return mainDeferred;
  });

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

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Field labels remain visible even when corresponding input fields or selection options are hidden

I have implemented a Bootstrap form with the form-floating class on the controls. An issue arises when certain controls are hidden, causing the labels to remain visible and become congested. Oddly enough, this only occurs with some controls while others b ...

How can I convert a Java array of arrays into JavaScript?

When working with Java, I need to create a JSON structure similar to this: [ [ timestamp , number ],[ timestamp , number ] ] This structure is necessary for displaying data on Highcharts graphs. I initially used a "LinkedList of LinkedList" format to ...

Using C# to generate a JSON array by extracting information from a CSV file

I am trying to generate JSON data in C# by pulling information from a CSV file. The desired JSON structure is shown below: { "car":[ { "manufacturer": "Nissan", "fuelType": "p ...

Unable to input any text into the textfield

After implementing redux-form-material-ui for my form, I am facing an issue where I cannot type anything in the textfield. Despite having two textfields and an Autocomplete option, only the Autocomplete box seems to be functioning properly while the textfi ...

Retrieve text excluding a specific class or id using jQuery

I need help with extracting text from an HTML div. <div id="example"> I am writing a <span class='outer'>query for help <span class='inner'>on a coding forum</span></span> </div> const te ...

Issue with jQuery animation: Background color does not change upon scrolling

Here is my fiddle link: https://jsfiddle.net/jzhang172/owkqmtcc/5/ I am attempting to change the background color of the "content" div when scrolling anywhere within it. The goal is for the background color to change when scrolling and revert back to its ...

Incorporate a new node module into your Ember CLI application

I am interested in integrating the Node.js module https://www.npmjs.com/package/remarkable-regexp into my Ember-CLI project. Can someone guide me on how to make it accessible within the Ember application? I attempted to do so by including the following c ...

Watch the Newest Vimeo Showcase Reel

I have a new project where my client is requesting to display the latest video from a specific Vimeo Portfolio. I already have a script that can fetch the latest video from the entire account using JavaScript as shown below: http://codepen.io/buschschwick ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Adjust the TextArea content according to the quantity of selections made in the listbox

If I have a listbox alongside a textarea: <textarea id="MyTextArea"></textarea> <select id="SelectList" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="me ...

Adjust fancybox height using jQuery

I am working on a project where I need to display a fancybox containing an iframe from another domain. The iframe has dynamic content and its height may change based on the pages it navigates to or the content it displays. I have access to the code of the ...

Display all options by clicking using the Chips and autocomplete features of AngularJS Material

I am utilizing the md-contact-chips component in a AngularJS application with autocomplete feature. As someone who is new to Angular, I am currently exploring ways to display the entire list of options immediately upon clicking the input field, rather than ...

Having trouble with the installation of Parcel bundler via npm

Issue encountered while trying to install Parcel bundler for my React project using npm package manager. The terminal displayed a warning/error message during the command npm i parcel-bundler: npm WARN deprecated [email protected]: core-js@<3 is ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Unexpected Error: The axiosCookieJarSupport function is throwing a TypeError, functioning properly in Node.JS but not in .vue pages. What could

Struggling with a function that authenticates on a website, it runs smoothly in a basic node.js script but fails when executed from a .vue page within the NuxtJS framework. The error message received when running in the .vue page is TypeError: axiosCookie ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Vue alert: The instance does not have a defined "hp" property or method, but it is referenced during rendering

Below is the code snippet that I am currently working with: var example1; var hp = ["p"]; document.addEventListener("DOMContentLoaded", function(event) { hp = ["x"]; example1 = new Vue({ el: '#example-1', data: { iLoveMysel ...

My intention is to ensure that the page is printed with the Background graphics checkbox pre-checked

When using the print button, I typically include the following code: onclick="window.print();" I also came across this code snippet to set a checkbox as checked by default: <style type="text/css" media="print"> * { -webkit-print-color- ...