The for loop finishes execution before the Observable in Angular emits its values

I am currently using a function called syncOnRoute() that returns a Promise. This function is responsible for synchronizing my data to the API multiple times based on the length of the data, and it returns a string message each time. However, I am facing an issue where the for loop completes before receiving the message from the API server.

Can someone please assist me with this?

 syncOnRoute() {
    return new Promise((resolve, reject) => {
      this.auth.database.executeSql('select * from onroute where HaveData=?', 
        ['yes']).then((res) => { //will retrieve 3 pieces of data from the Database

        for (let i = 0; i < res.rows.length; i++) { // will execute 3 times
                        
                let params = new HttpParams()
                  .set('CLAIMGUID', res.rows.item(i)['CLAIMGUID'])
                  .set('JOBGUID', res.rows.item(i)['JOBGUID'])
                  .set('Latitude', res.rows.item(i)['Latitude'])
                  .set('Longitude', res.rows.item(i)['Longitude'])
                  .set('OnRouteDT', res.rows.item(i)['OnRouteDT'])
                  .set('Desc', this.auth.getdateformatV2())
                  .set('title', 'onroute');
                  this.auth.httpSend('Service_SaveOnRoute', params, 'post').subscribe((msg) => {
                    console.log('##SUCCESS ONROUTE SYNC' + JSON.stringify(msg)); // receiving return msg from API

                  }, 
                  (err) => {
                    console.log('##SUCCESS ONROUTE SYNC' + JSON.stringify(err));
                     
                  }
                );
} // the for loop completes before receiving return msg from API
                
                   
x

Here is my httpSent() method, which returns an Observable

public httpSend(endPoint:string, params:HttpParams , method: string){
    
    switch(method){

      case 'post':{
        return  this.httpClient.post<any>("https://ws-v3test.ventureprise.cloud/Service1.asmx/"+endPoint,params);

      }
      break;
      case 'get':{
        return  this.httpClient.get<any>("https://ws-v3test.ventureprise.cloud/Service1.asmx/"+endPoint);

      }
    }
  }

Answer №1

If you want to make a change, consider swapping out subscribe for toPromise and utilize for...of with await

Another option is to gather all instances of this.auth.httpSend('Service_SaveOnRoute', params, 'post') in an array and wait for them all to complete after the loop ends

I trust this advice will be useful to you! Happy coding!

Check out this link for more information on for await...of loop

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

Using the Restangular response with ng-repeat

Currently, I am delving into the world of angularjs with restangular to interact with my RESTful API (sails). However, I have run into an issue where the ng-repeat does not refresh after modifying the list in the scope. Here is the Controller: app.contro ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

What is the process for storing user-provided document names in Firestore database entries?

I'm encountering an issue with my API while trying to utilize Firestore for inputting data for login and registration via the API. The problem arises when attempting to add a document entry in the database with the user's input email during regis ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

Performing an Axios POST request in a React Native and React app using JSON.stringify and Blob functionality

I am currently developing an application where I have encountered an issue when calling an API endpoint in react native. Interestingly, the web app (built with React) does not encounter any errors. Here is the code for the web app using React with TypeScri ...

Creating a text file in Node.js using nodepad formatting

Could anyone assist me with formatting text in a Node.js file to be written to Notepad? Here's the code I'm currently using: const fs = require('fs'); fs.writeFile('write.txt', '', err => {}); var text = [ ...

Troubleshooting Async Function compatibility between Express and NestJs

Initially, I set up a small express server to handle report generation and file writing tasks. var ssrs = require('mssql-ssrs'); var fs = require('fs'); const express = require('express') const app = express() const port = 30 ...

Tips for handling Google Spanner Date type in JavaScript

I am facing a challenge with Google Cloud Spanner as I work with multiple tables containing columns of type Date. While inserting entries with specified dates works fine, the issue arises when trying to retrieve these entries in the JavaScript frontend. Th ...

Using setState in an external function: A step-by-step guide

import Request from 'superagent'; const fetchApi = () => { let apiUrl = '/* URL */'; return Request.get(apiUrl).then((response) => { this.setState({ data: response.body }); }); } export d ...

An obstacle prevents the code injection process in the Chrome extension when a button is pressed

My basic chrome extension is not functioning correctly. More specifically, I am encountering an issue where the alert box does not appear when I click on the button in the popup. Here are the contents of my manifest.json file: {"manifest_version": 2, "n ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

Exploring the dynamic changes in user authentication state with Angular Fire subscriptions

At the moment, I have been listening to authentication state changes in my ngOnInit method of my AppComponent: export class AppComponent implements OnInit { constructor(public fireAuth: AngularFireAuth) { } ngOnInit(): void { this.fireAuth.auth ...

Discover the process for finding a Youtube Channel Name with querySelectorAll

OUTPUT : Console URL : https://www.youtube.com/feed/trending?gl=IN document.querySelectorAll('a[class="yt-simple-endpoint style-scope yt-formatted-string"]')[0].innerText; document.querySelectorAll('a[class="yt-simple-endpoi ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

Different ways to alter response headers using express-http-proxy

Context In my current project, I am utilizing the express-http-proxy package to facilitate requests between a Single Page Application (SPA) and a CouchDB instance. I have opted for handling this proxy setup on a per call basis rather than creating a dedic ...

Perform actions while HTML5 video is in progress

I've been attempting to trigger a simple function when an HTML5 video hits a specific second mark, but so far I haven't had any success. I'm reaching out for assistance and guidance. Below is the code I have been working with: jQuery(functi ...

Error: Unable to assign values to undefined properties (specifically 'styles') when using withLess, withSass, or withCSS in next.config.js within Next.js

I have been attempting to set up a NextJS 12 project with custom Ant Design. Following some examples I found, it seems I need to configure my next.config.js file with the libraries @zeit/next-sass, @zeit/next-less, and @zeit/next-css. However, when I try t ...

Invoke a jQuery function in the parent page using regular JavaScript from an iframe

I have successfully created an iframe using regular javascript. Inside the iframe is a Jquery function along with JQuery itself and it functions correctly within the iframe. However, I am now looking to execute this function from the parent page instead of ...