Empty promise will be followed by an array that is empty

How can I fetch time from Firestore using a promise in Angular CLI 8, but the array is empty because the promise has not resolved yet? How can I ensure the array is only called after the getTime() function has finished executing?

example.service.ts

teste: [];

getTime() {
    this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('No timestamps available at the moment, please wait')
        } else {
          res.forEach(ponto => {
            console.log(ponto.id);
            console.log(ponto.data().time.seconds * 1000);
            this.time.push(new Date((ponto.data().time.seconds * 1000)));
          })
        }
      }).catch(err => {
        console.log(err);
      })
  }
example.component.ts

ngOnInit() {
    this.mainService.getTime();
    console.log(this.mainService.time);
  }

I want the array variable to be populated by the time data when I access it.

Answer №1

You may implement the use of async and await for asynchronous operations.

Within the service:

fetchTimeData() {
    return this.userCollection.ref.get()
      .then(res => {
        if (res.docs.length == 0) {
          alert('No time entries found, please wait')
        } else {
          res.forEach(entry => {
            console.log(entry.id);
            console.log(entry.data().time.seconds * 1000);
            this.time.push(new Date((entry.data().time.seconds * 1000)));
          })
        }
        return true;
      }).catch(err => {
        console.log(err);
      })
  }

Within the component:

async initializeTime() {
    await this.mainService.fetchTimeData();
    console.log(this.mainService.time);
}

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

Tips on Handling Multiple Versions of jQuery

I'm seeking your guidance on a particular issue at hand. I am part of the development team for a large web application that heavily relies on jQuery and has been in constant development for the past 7-8 years. Over this time, several versions of jQue ...

Configuring Angular to use ES6 syntax

Trying to integrate angular google maps with es6 syntax has been a challenge for me. In es5, the code typically looks like this: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider.configure({ // key: 'your api key&ap ...

Error: The method `push` within the `useHistory` function is causing an issue and is currently undefined

Whenever the home button is clicked, I need it to redirect to the homepage '/ '. However, I keep encountering this error. Any suggestions on what steps I should take to resolve this? : import { Route, useHistory } from 'react-router-dom/cjs/ ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

sort the array based on its data type

Recently diving into typescript... I have an array that is a union of typeA[] | typeB[] but I am looking to filter based on the object's type interface TypeA { attribute1: string attribute2: string } interface TypeB { attribute3: string attri ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

The webpage is missing a rendered React component even though it should be displayed

I am facing an issue where a React component is not appearing on the webpage despite being rendered. I have provided the code and screenshots of the components below for reference. Below is the snippet from the "App.jsx" file: function createCard ...

Solution: How to fix the error: Invalid component type, 'Draggable' cannot be used with JSX in react-draggable

I encountered an error while working on this Next.js React project Type error: 'Draggable' cannot be used as a JSX component. Its instance type 'Draggable' is not a valid JSX element. The types returned by 'render()&apo ...

What is the best way to check the value of a Reference type in a CDK stack

I have successfully created resources using the aws cdk library. I am now facing an issue with testing a stack that contains multiple resources. When testing a single resource, everything works fine, but I'm unsure how to test a stack with multiple re ...

Using a data() object in Vue to fill out form fields efficiently

My data retrieval process from mongodb involves obtaining the data and transferring it to the client side using the following approach: error_reporting(E_ALL); ini_set('display_errors', '1'); require '../vendor/autoload.php'; ...

Custom div element obstructs information window on map due to lack of auto panning feature

I created a unique div that is absolutely positioned on a Google Map. You can view the image below to see it. My issue is that the info window is being covered by this custom div element, as demonstrated in the picture. https://i.stack.imgur.com/1TgyQ.jpg ...

Angular: verifying the presence of any of the ng-content slots supplied

I have a component template that contains several ng-content elements: <div class="form__general"> <ng-content select="[general]"></ng-content> </div> <div class="form__footer"> <ng-conte ...

Having trouble executing the command ~$ vue add unit-mocha using vue cli 3

I am trying to integrate mocha as a unit testing plugin into my existing Vue project, which was set up using CLI 3 (vue create myProj). This pertains to Vue CLI version 3.0.0 and above, in which my current project is operating. Here is the error message ...

Learn how to easily copy the success result from an Ajax call to your clipboard

Is there a way to use an ajax method to retrieve data from a controller and display it in a JQuery Dialog Box? I want to add a button within the dialog box that allows the user to easily copy the data with a single click, instead of having to manually high ...

The Next.js build failed due to the absence of the required "slug" parameter being passed as a string

I'm currently working on setting up a blog using Next.js and TypeScript, and I've encountered an issue with [slug].tsx. The error message I'm receiving is: Build error occurred Error: A required parameter (slug) was not provided as a strin ...

The error message "Unable to create THREE.Points due to undefined or null object conversion" is

Within this code snippet, I conducted testing on the geometry and material variables with different return values. Interestingly, upon removing these variables, the error vanished. var actionZ = 0; var rotationA = 1.1; var movementSpeed = 1; var totalOb ...

Guide on transmitting information from a Kotlin-powered Android app to a React JS application being accessed through a WebView

Imagine you have logged into an Android application using Kotlin and have some data stored. Later, you open a React JS application in a webview. How would you go about transferring the login data from the Android application to the React JS application? ...

jQuery UI Sortable: Efficiently Drag Items Across Multiple Interconnected Lists

One feature of using jQuery UI Sortable is the ability to make the sortable item container scroll when an item is dragged. This can be achieved by specifying the scroll option. In my case, I have several sortable lists that are connected within separate c ...

Is it advisable to optimize your SEO by placing the JavaScript code at the bottom of your webpage?

Is this just an urban legend or is it actually true? I've heard that when web crawlers analyze a webpage, they have a time limit to capture all available code (like html) before moving on to the next page. If the JavaScript code is in the head sectio ...

What is the best way to track and document the specific Context Provider being utilized while invoking useContext?

After creating a custom component that displays AuthContext.Provider with specific values, I encountered an issue. Even though it functions correctly, when I utilize useContext within a child of the AuthProvider component, my code editor (VS Code) is unabl ...