Angular 5: Using Await But Not Actually Waiting

Upon executing the provided code, I noticed that the checkCard function is being triggered before the getTimecard function completes its execution.

getTimecard() {
  this._service.getTimecard().subscribe(
  data => {
    this.sending = true;
    this.timecards = data;
  },
  err => {
    this.sending = false;
    console.error(err);
  },
  () => {
    this.sending = false;
  }
);
}

checkCards() {
  console.log('timecards', this.timecards);
  //Additional code reliant on timecard data
}

async onSubmit() {
  await this.getTimecard();
  this.checkCards(); 
}

Could it be possible that the checkOverlap function is not waiting for the completion of the getTimecard function to fetch its data?

Answer №1

In order to make a function able to be awaited, it is necessary for the function to return a Promise.

fetchTimecards() {
   return new Promise(resolve => {
     this.loading = true;
     this._service.getTimecard().subscribe(response => {
       this.loading = false;
       this.timecards = response;
       resolve();
     });
  });
}

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

Bringing packages from around the world into your Node.js project

In my node.js application, I have several modules where I find myself importing the same package (e.g. moment npm). I'm curious if there is a more efficient way to handle imports by centralizing all dependencies in one place and using them as global ...

Displaying dynamic json responses in Angular 9 with line numbers added

Seeking a solution to efficiently display a dynamic Json response received from the server, the structure of which typically resembles: { responseBody: { menu: { id: 'file', value: 'File', }, }, } stat ...

Error occurs in React Native when trying to import routes due to type mismatch

My react native app is running on my physical device, but I encountered an error when importing routesContainer in my app.js. Can anyone shed some light on why this error is occurring? TypeError: Super expression must either be null or a function [Mon Oct ...

Instructions for utilizing a non-string reference without triggering flow errors

I've noticed that string refs are considered legacy in React. You can read more about it here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md However, I am encountering a flow error in my component and I&apo ...

Steps to expand, collapse, and append new lines to a div by clicking a button:

I have a set of divs and I'm looking to implement a feature that allows users to dynamically add more div elements to the form when they click on the Expand/Collapse button, similar to the image provided. I've attempted the code below, but it do ...

Determine the class for a div within *ngFor by evaluating a condition

I am facing an issue where I need to dynamically assign a class to a div element within a *ngFor loop based on a method. Below is the code snippet from my HTML file: <ng-container *ngFor="let data of totalData let j = index"> < ...

What are the best practices for integrating Typescript with CodeceptJS for testing automation?

Looking for assistance in setting up a testing framework with CodeceptJS, using TypeScript instead of JavaScript for writing page objects and tests. Does anyone know what configuration is needed in the conf.js or steps.ts files? In my conf file, I have ad ...

Implementing HTTP GET and POST requests in Angular 2 allows for the functionality of displaying, adding, and deleting objects within a list

Hey there, I'm completely new to dealing with HTTP and fetching data from the server. I've been scouring through various tutorials, examples, and questions on different platforms, but unfortunately, I haven't been able to find exactly what I ...

View saved local storage information

I have an inquiry regarding saving data using localStorage for a shopping cart feature. I am able to list the data on one page through console.log but am facing difficulties in calling the data on another page. Can anyone assist with this? The Product page ...

JSON object containing multiple elements in JavaScript

I have a JavaScript JSON object const student = { name: "bob", age: 7, grade: 6 } and I can send it to my Web API using the axios POST command with JSON.stringify(student) To build multiple student objects from an array by looping through and p ...

I would like to create a fixed-position menu similar to Slashdot's comment filtration menu. How can I achieve this?

Have you ever noticed that Slashdot has a cool little feature that lets you adjust your comment threshold to filter out down-modded comments? When you scroll to the top of the page, it stays in one place, but as you continue scrolling down, it eventually s ...

How to change the return type of a method with multiple overloads in TypeScript

I am currently developing an open-source library that creates Proxies for Rx Observables. (For the sake of simplicity, I will use Box<A> instead of Observable<A>) The library takes a Box<A> as input and returns a type { [P in keyof A]: ...

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

What is the process of retrieving data from a Nextjs API route during the build and deployment stages?

I'm currently facing an issue while trying to deploy my nextjs web app on vercel. Upon deployment, I encounter the following error: > Build error occurred FetchError: request to http://localhost:3000/api/products failed, reason: connect ECONNREFUS ...

"Prop serves as a blank slate within the child component of a React application

My current challenge involves integrating a search bar into a parent component. Despite successful logic in the console, I am experiencing a reduction in search results with each character entered into the search field. The issue arises when attempting to ...

WordPress: Issue with Dropdown onchange Event Not Triggering

I'm having trouble getting an event to fire when the dropdown value changes. Can anyone help me figure out where I might be going wrong? JavaScript code jQuery(document).ready(function($){ jQuery('#_ccounts select').on('change&apo ...

Issue with arrow functions not functioning correctly in the browser

Implementing the following method works effectively. var DBBox = React.createClass({ loadArticlesFromServer: function() { $.ajax({ url: this.props.url, dataType: 'json', data: {username:data.username,isPublished:data.isPublished, ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

The property you are trying to access is not found within the declared type of 'IntrinsicAttributes & { children?: ReactNode; }'

In my React project created using Create-React-App, I have included the following packages (relevant to the issue at hand): "react": "^16.13.1", "react-dom": "^16.13.1", "react-router-dom": "^5.1.2", "react-scripts": "3.4.1", "typescript": "^3.9.2", "@typ ...

Smooth sailing ahead: no anticipated issues with axios and express router

I am encountering an issue while trying to request third party APIs from my API. The response I receive is always an empty document. module.exports = app => { const servicesToll = (req, res) => { var obj try { con ...