Antoine Turcotte
Antoine Turcotte

Reputation: 35

Typescript non-empty Array return length of size zero

Currently having trouble understanding the problem with my following piece of code. Any advices or informations are more than welcome!

getProjects(client):string[] {
      client = client.trim();

      var tempProjects = [];
  
      // if(this.m_projects.length >= 1){
      //   this.m_projects = [];
      //   this.m_tasks = [];
      //   this.sTask = null;
      //   this.sProject = null;
      // }
      
      
      const curTaskObservable = this.afs.collection('users').doc('myFirstUser')
      .collection('clients').doc(client).collection('projects')
      .valueChanges()
      .subscribe((data:any)=>{
        data.forEach(el=>{
          if(this.m_projects.indexOf(el.name) === -1){
            this.m_projects.push(el.name);
            tempProjects.push(el.name);
          } 
        });
      });
      
      console.log("array length : " + tempProjects.length);
      console.log(" array content : " + tempProjects);
      return tempProjects;

The output, as shown below prints the length "0" and for the array content, the length "1". How can that be possible, and is there a way to get the correct length value. Thank you!

The output of the console logs

Upvotes: 2

Views: 573

Answers (1)

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 18909

subscribe((data:any)=>{
        data.forEach(el=>{
          if(this.m_projects.indexOf(el.name) === -1){
            this.m_projects.push(el.name);
            tempProjects.push(el.name);
          } 
        });
      });
      
      console.log("array length : " + tempProjects.length);
      console.log(" array content : " + tempProjects);
      return tempProjects;

It is not that the array is empty. It is that you have not yet understand how asynchronous code get's executed. The block inside the subscription can be executed after the console.log which prints the array size.

Move the console.log inside the subscription block.

 subscribe((data:any)=>{
            data.forEach(el=>{
              if(this.m_projects.indexOf(el.name) === -1){
                this.m_projects.push(el.name);
                tempProjects.push(el.name);
                console.log("array length : " + tempProjects.length);
              } 
            });
          });

This would be a good step to understand how asynchronous code works.

Upvotes: 3

Related Questions