How to stop a loop of method calls that return a Promise<any> in TypeScript

My current issue involves a loop in which a method is called, and the method returns an object of type Promise<any>. I need to break the loop if the response from the method is correct. However, using the break statement does not stop the loop as expected:

for (let item of List) {
  let currentItem = item.split(',');
  
  if (flag != '0')
  {
    break;
    
  }
  this.service.getList(currentItem[0]).then(res => {
    if (res != null) {
      for (let i of res) {
        if (i.serviceName == name) {
          flag = selectIp;
                
          break;
        }
      }
    }
  }).catch(res => {

  });

}

The relevant code from the Service:

getList(ip: string): Promise<any> {
  const apiUrl = environment.url + '/getData';
  return this.httpClient.post<any>(apiUrl, body)
    .toPromise();

}

The issue I am facing is that the break statement is not functioning correctly. The loop continues even when both flag != '0' and i.serviceName == name.

Answer №1

Feel free to utilize the following code snippet. Ensure that your function is asynchronous and utilize the await keyword as shown below:

for (let item of List) {

  let currentItem = item.split(',');
      
  if (flag != '0')
  {
    break;
  }

  const res = await this.service.getList(currentItem [0]);

  if (res != null) {
    for (let i of res) {
      if (i.serviceName == name) {
        flag = selectIp;         
        break;
      }
    }
  }
    
}

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

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far: function customFunction<T = any>(input ...

The type 'ReadableStream<any>' cannot be assigned to the parameter type 'ReadableStream'

Is there a way to convert a Blob into a Readable format? import {Readable} from 'stream'; const data: Blob = new Blob( ); const myReadable: Readable = (new Readable()).wrap(data.stream()); myReadable.pipe(ext); Encountering an error: ERROR in s ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...

Creating a package exclusively for types on NPM: A step-by-step guide

I'm looking to set up a package (using either a monorepo or NPM) that specifically exports types, allowing me to easily import them into my project. However, I've run into some issues with my current approach. import type { MyType } from '@a ...

File declaration for modules within modules

I'm currently working on a project that includes a Node JS module located at foo/bar.js. As I'm developing a TypeScript module in src/mymod.ts that needs to import foo/bar.js, I'm facing a challenge in creating a declarations file for the fo ...

Accessing data from a reactive source within a component

Upon building a component, I encountered an issue with returning a property containing an observable. While I was able to successfully display the property in the template, I realized that its presence there was unnecessary: {{(selectedOrder$ | async).ord ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

Having difficulty in utilizing localStorage to update the state

I've attempted to log back in using the stored credentials, however it's not working despite trying everything. The dispatch function is functioning properly with the form, but not when accessing localStorage. App.tsx : useEffect(() => { ...

What is the step-by-step process for incorporating the `module` module into a Vue project?

ERROR Compilation failed with 6 errors 16:20:36 This specific dependency could not be located: * module in ./node_modules/@eslint/ ...

Generating a Radio Button Label on-the-fly using Angular 8 with Typescript, HTML, and SCSS

Struggling with generating a radio button name dynamically? Looking to learn how to dynamically generate a radio button name in your HTML code? Check out the snippet below: <table> <td> <input type="radio" #radio [id]="inputId" ...

ngx-charts-pie-chart angular5 library data structure

I am utilizing the ngx-charts library in my current project. When using the onSelect method, I noticed that it only returns an object with attributes value and name, even though my list contains three attributes: value, name, and id. Upon examining the s ...

Unable to successfully transfer a document

I am looking to upload a file onto my server. Here is what I have attempted: <input (change)="uploadImage($event.target)" hidden accept="image/*" #uploadProfileImage type="file"> uploadImage(event) { const profileImage = event.files.item(0); t ...

The header of the function specifies only one parameter, however the function call necessitates three

Within my Typescript code, I have a function defined as follows: export const func: AWSLambda.APIGatewayProxyHandler = async ( arg ): Promise<AWSLambda.APIGatewayProxyResult> => { During a unit test, when I attempt to call this function like fu ...

Testing the behavior of Angular components by focusing on specific services at the component level

Within my Angular application, I have a service that is specifically provided at the component level: @Component({ selector: 'my-component', templateUrl: './my.component.html', providers: [MyService], }) export class MyComponent i ...

Using Typescript to define a method that returns a value within a .then() function

Currently in the process of coding a function to add a user to a database, with the requirement of returning a promise with the specified User class that I have created: async createUser(user: User): Promise<User> { const userObject: User = user; ha ...

Struggling to synchronize the newly updated Products List array in zustand?

Let me clarify the scenario I am dealing with so you can grasp it better. I have a Cart and various Products. When a user adds the product (product_id = 1) twice to the cart with the same options (red, xl), I increase the quantity of that item. However, i ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

Interface definition triggers an error when assigning a string literal to a field

When defining a string literal type in an interface, I encountered unexpected behaviors. interface IFoo { value: 'foo' | 'boo'; } Upon implementation of the interface in a class, I encountered an error: class Foo implements IFoo ...

A type guard for generics in TypeScript

I'm dealing with a variable that can be either of type C1[] or C2<C1>[]. How can I create a type guard for this variable? interface C<T>{ key: string; secret: T; } private isC(d: Foo[] | C<Foo>): d is C<Foo>[] { ret ...