Angular is encountering a situation where code is being executed before properly waiting for the response from an asynchronous

I am in need of a solution that will ensure my function waits for a response before proceeding. I want to prevent the response from being empty and ensure that my code waits for the completion of the asynchronous call.

asyncReq(element: any) {
  this.conflictData = null;
  //For entire day
  let startDate: any;
  let endDate: any;
  startDate = this.easternToUtc.transform(moment(element.START_TIME).format('YYYY/MM/DD 00:00:00'), this.selectedTimeZone);
  endDate = this.easternToUtc.transform(moment(element.END_TIME).format('YYYY/MM/DD 23:59:59'), this.selectedTimeZone);
  return new Promise((resolve, reject) => {
    let requestPayload = zipObj(['USER_ID', 'AMENITY_TYPE_ID', 'AMENITY_ID', 'START_TIME', 'END_TIME', 'BUILDING_ID', 'AMENITY_NAME'], [element.USER_ID, element.AMENITY_TYPE_ID, element.AMENITY_ID, startDate,
      endDate, element.BUILDING_ID, element.AMENITY_NAME
    ]);
    this.http.post(`${environment.reservationValidation}`, requestPayload).pipe(take(1)).subscribe(e => {}, (e: any) => {
      console.log(e);
      element.ERROR_TYPE = e.error ? .message;
      element.HAS_ERROR = true;
      this.conflictData = e.error ? .reservationdata;
    })
  })
}

async validateRecords(data: any, step: any): Promise < void > {
  return new Promise(async(resolve, reject) => {
    try {
      data.forEach(async(element: any) => {
        await this.asyncReq(element);
      })
      // this.errorCount = await this.finalData.filter(a=>a.HAS_ERROR).length;
      // console.log(this.errorCount,"error Count");
      console.log(this.finalData);
      const errors = await this.finalData.filter((ele) => ele.HAS_ERROR)
      console.log("errors", errors); // always returning empty array though the value of ele.HAS_ERROR is true bcoz this is calling before waiting for response.
      this.errorCount = errors.length; // this is always giving 0 
      setTimeout(() => {
        this.step = step;
      }, 800)
    } catch {
      console.log('Some Error');
    }
  })
}

I am seeking assistance in ensuring that the response is not empty and that the code waits for the completion of the asynchronous call. Can someone provide guidance?

Answer №1

The issue lies within the forEach method using async/await with forEach may lead to compatibility issues

data.forEach(async(element: any) => {
    await this.asyncReq(element);
})

By switching to for loop, the problem can be resolved

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

Utilizing Vue to bind data for asynchronous Axios requests

Having an issue with my Vue function that is triggered by a button click. It makes an axios call, but the problem is that no matter what I type in the textarea (v-model taskCommentBody), it sends the data commentBody as blank. Not sure what's causing ...

Dynamically importing files in Vue.js is an efficient way to

Here's the code snippet that is functioning correctly for me var Index = require('./theme/dir1/index.vue'); However, I would like to utilize it in this way instead, var path = './theme/'+variable+'/index.vue'; var Inde ...

Creating a custom JavaScript function to manipulate arrays

I am working on a project involving an array of strings that represent class names. My goal is to instantiate these classes using their string names, but so far my attempts with the window object have been unsuccessful. The array structure looks like this ...

Error: Unable to assign value to the property 'address' as it is undefined in SafeSubscriber._next

Struggling to pass data to an array that is declared inside the component. Only the first index of the array is being returned, while the other elements are not. I've learned that the program works asynchronously and only retrieves the first index. S ...

The true essence of Angular values only comes to light once the view has been updated

Here is the HTML code I am working with : <div class="container-fluid"> <div class="jumbotron" id="welcomehead"> <br><br><br><br><br><br><br><br><br><br> ...

Upload file via AJAX immediately after downloading it (no need for storage)

Currently, I am in the process of developing a JavaScript script to safeguard an old game development sandbox website from being discarded by its owners. In order to prevent the loss of all the games on the site, I have managed to create a script that allo ...

Angular-Slickgrid displaying empty data entries

Currently, I am attempting to implement a grid option in my application using the angular slickgrid library. Despite referencing the wiki page for guidance on displaying the grid, I am facing the issue of no data appearing in the grid, and there are no err ...

Implementing jquery document.ready() with <img onload> event

My current need is to trigger a JavaScript function each time an image loads on the page, but I also require that the DOM of the page is fully loaded before the script executes. I have provided a sample example below and would appreciate feedback on wheth ...

The mysterious Vue.js and Nuxt.js custom element

Encountering an issue https://i.sstatic.net/imRbe.png Seeking assistance with identifying my mistake. Attempting to create reusable components, starting with a button for example. I have created it in the file path: /components/MusicPlayer.vue: <temp ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

Utilize ModifyDOM to erase text triggered by selecting a radio button

I have created a form that includes four radio buttons along with a reset button to clear the form. When a radio button is selected, information is displayed using "displayText". I am looking to add an onclick handler to trigger a function that will delete ...

Extracting a compilation of video content from a YouTube channel through JSON data retrieval

I'm struggling to display the 5 most recent videos (title, updated, thumbnail (hqDefault)) from a specific channel using JSON data. I've tried various guides but can't seem to parse it correctly. Any suggestions on how to achieve this? I&apo ...

Custom label slots in q-file for the Quasar file picker for personalized file selection label

Can you provide guidance on how to properly display custom label slots in Quasar? I am looking to incorporate icons or images using the label slot. Below is my data(): data() { return { showLabel: true, labelText: "My custom Label& ...

Unable to attach a javascript eventListener to a newly created element

I've utilized JavaScript to generate 625 <div class="box"><div> elements and now I'm trying to attach an event listener to each box. The boxes are being created successfully, however, the listener does not seem to be working ...

Is there a way to inform the List component when the height of its row items has been altered in order to trigger a rerender

In my project, I am using a react-virtualized List where each item in the rows has an expand button. When this button is clicked, the row's height changes to reveal more information. The problem I am facing is that after clicking the button, the inne ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

How can I alter the appearance of HTML text when hovering over the enclosing div?

I want the text to change color and zoom when the cursor is near it (when the mouse enters the area of the div containing the text). Currently, I am able to change the text color only when hovering directly over it. Below is a snippet of the code. HTML: & ...

Can the AngularJS icon adapt to different lists?

I'm currently developing in AngularJS / Jade and I need to implement functionality where an icon changes when a user clicks on something. The code I have right now looks like this: a(onclick='return false', href='#general', data-t ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

Master the art of string slicing in JavaScript with these simple steps

I am attempting to utilize the slice function to remove the first three characters of a string within a JSON object. $(document).ready(function() { $.ajaxSetup({ cache: false }); setInterval(function() { $.getJSON("IOCounter.html", functio ...