The array is displaying values despite having a length of 0

When querying a firebase database and pushing the results into an array to remove duplicates, everything appears to be working fine. However, I am encountering an issue where the length of the final array is 0 even though there is data present.

let interests = [
  '-KpUpVi7-2W_JmR16HuC',
  '-KpUpYwC_FRulbXZnULK',
  '-Kpd3J9gNECwWSG6xAvt',
  '-KpUpbP3AGKs28McNrBh'
]
let finalArray = [];
interests.forEach((interest) => {
  this.hangoutsService.getInterestUsers(interest)
  .subscribe(
    (res) => {
      //console.log('the results: ', res)
      res.forEach((uid) => {
        //console.log(uid)
        finalArray.push(uid)
      })

    }
  )
})
console.log('final array: ',finalArray)
console.log('final array length: ',finalArray.length)

This is the method being called:

  getInterestUsers(interest){
  return this.db.object(`usersPerInterest/${interest}`)
    .map((r) => {
        return Object.keys(r)
    })
}

A screenshot of the console can be viewed here.

I'm unsure what I might be missing here. Any insights?

Answer №1

Your implementation involves callbacks, but there is an issue where the array is being printed before receiving a response from the callback.

let interests = [
  '-KpUpVi7-2W_JmR16HuC',
  '-KpUpYwC_FRulbXZnULK',
  '-Kpd3J9gNECwWSG6xAvt',
  '-KpUpbP3AGKs28McNrBh'
]
let finalArray = [];
interests.forEach((interest) => {
  this.hangoutsService.getInterestUsers(interest)
  .subscribe(
    (res) => {
      //console.log('the results: ', res)
      res.forEach((uid) => {
        //console.log(uid)
        finalArray.push(uid)
      })
    console.log('final array: ',finalArray)
    console.log('final array length: ',finalArray.length)
    }
  )
})

An alternative approach to address this issue is by using promises instead of callbacks.

Answer №2

Make sure to log the array length inside the asynchronous callback function instead of outside. The callback function may still be processing when you log the array length immediately after it.

console.log('final array: ',finalArray)
console.log('final array length: ',finalArray.length)

This is why you are seeing an empty array. To accurately track the result of an asynchronous function, place your console logs within the asynchronous function itself.

let finalArray = [];
interests.forEach((interest) => {
  this.hangoutsService.getInterestUsers(interest)
  .subscribe(
    (res) => {
      // console.log('the results: ', res)
      res.forEach((uid) => {
        // console.log(uid)
        finalArray.push(uid)
      })
        console.log('final array: ',finalArray)
       console.log('final array length: ',finalArray.length)
    }
  )
})

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

creating a nested JavaScript object within another object

I need to create an object using the angular.forEach() function and then push another object while initializing all values to false. However, the current approach is causing errors. How can I achieve this correctly? Using "item.id" and "index.id" does not ...

"Exploring locations with Google Maps and integrating them into interactive

I recently encountered an issue while working on a node express application and integrating the google maps javascript api. The problem arose when I attempted to transfer the sample code from the google website, along with my API key, into a .ejs file. S ...

The presence of foreign collections does not appear to be reflected in the combined data

I am developing a basic forum and I'm looking to connect two databases so I can show information about the user who created a post on that post: User.js: _id:60ccb13a21d65f0c7c4c0690 username: testuser name: test And Createpost.js _id:60d80b1305dcc5 ...

Following the parsing of the list of months, the sequence undergoes a

After receiving the JSON encoded object from the server side in PHP MONTHLY_FORMAT, I am reading that object in jQuery as: var MONTHLY_FORMAT = '<?php echo $MONTHLY_FORMAT; ?>'; When checking the console output, it looks like this: {"0 ...

The dropdown menu is experiencing issues on a compact mobile display when using React Bootstrap

Utilizing a dropdown list on a compact screen such as mobile can result in a poor user experience when using the react bootstrap dropdown list. Are there any alternative libraries available that provide a more seamless action sheet appearance for Reactjs, ...

The condition to break when a value is found within a specific range on sheet1 if it is present in the range on

Essentially, the user will input data for a new item on the NovoItem sheet. Upon pressing the Save Button (yet to be added), the code should check the ArquivoItens sheet to see if the item already exists. If it does, the code should halt its operation. Ho ...

Gridsome's createPages and createManagedPages functions do not generate pages that are viewable by users

Within my gridsome.server.js, the code snippet I have is as follows: api.createManagedPages(async ({ createPage }) => { const { data } = await axios.get('https://members-api.parliament.uk/api/Location/Constituency/Search?skip=0&take ...

Creating an accordion using an array in JavaScript: A step-by-step guide

I'm experimenting with creating an accordion using HTML, CSS, and JavaScript. I've managed to set it up, however, the array text is only displaying in one accordion item and the buttons are not functioning for each individual accordion. Is there ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Is there a way to display a multidimensional array according to the key?

I have an array that contains multiple dimensions as shown below: $adminoptions = array(array("hello","replies",0),array("goodbye","replies",1),array("hola","flagged",0)); What I want to achieve is to extract 'goodbye', 'replies' and ...

Unexpected behavior observed when using React useEffect

useEffect(() => { const method = methodsToRun[0]; let results = []; if (method) { let paramsTypes = method[1].map(param => param[0][2]); let runAlgo = window.wasm.cwrap(method[0], 'string', paramsTypes); //this is em ...

Guidelines for placing an HTML element in relation to another HTML element using CSS or JavaScript

Is there a way to position an HTML element in relation to another using CSS or JavaScript? I have attempted to copy the inner HTML of the "second-element" and append it inside the "first-element", but this approach is causing issues with other functional ...

Are the import and export keywords native to webpack or are they specific to JavaScript syntax?

I am pondering whether the import & export aspects are part of the language itself or simply keywords that webpack adds to the language. Thank you. ...

BiQuadFilters vs. Personalized Filter - Harnessing the Power of the Javascript WebAudio API

As part of my downsampling process from 48kHz to 16kHz, I need a filter to prevent aliasing. Thankfully, the WebAudio API provides built-in filters that I can utilize: biquadFilter = context.createBiquadFilter(); biquadFilter.type = "lowpass"; biquadFilte ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

Is your Angular2 form page experiencing reloading issues?

I am currently incorporating Angular2 into my project. I am facing an issue where the page keeps refreshing, and I'm unable to determine the cause. Below is a snippet of my form: <form> <div class="form-group"> ...

Is window.open exclusive to Firefox?

Apologies if this question has been asked before! I am experiencing some issues with my Javascript code. It works perfectly in Firefox and opens a pop-up window as expected. However, in IE 9 it does nothing, and in Chrome it behaves like a link and change ...

Is there a way to cancel an ongoing AJAX request?

My website will soon have a series of jQuery AJAX calls, and I need to create a function to abort these calls. Can anyone provide guidance on how to achieve this? I have already reviewed this particular link, but it did not work for me as expected. ...

Adding a timestamp to an array in Angular/Typescript services

I've been struggling with adding a timestamp OnInnit to track the time a user visited a page. I want to include the timestamp in an array within my services, but I keep encountering errors and can't seem to figure it out on my own. Any assistance ...

Issue with Node.js server - appending a "/" when searching for files on browser

Currently, I am in the process of building my very first Node.js server to gain a better understanding of Angular/Node and ultimately explore the entire MEAN stack. Although my server is operational, there seems to be an issue within my code. Whenever I i ...