Guide to running asynchronous code synchronously in Angular 5

Currently, I have a function that loops through a list of files and for each file, it triggers an async method to manipulate the image and add it to an array.

The problem is that the async calls are occurring simultaneously, causing the UI to freeze. My goal is to iterate through the list sequentially, waiting for each task to finish before moving on to the next one.

Array.from(files).forEach(data => {
    if (data.size > 5000000) {
        this.toastr_service.error('FILE ' + data.name + ' EXCEEDS FILE SIZE LIMIT (5MB)');
    }else {
        this.asyncFunc(data).subscribe(result => {
            this._photos.push(result);
        }, error => {
            console.log(error);
        });
    }
});

Answer №1

Utilize the map method of arrays along with RxJS's forkJoin

forkJoin(Array
  .from(files)
  .map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
  .filter(value => !!value)
).subscribe(([...responses]) => {
  console.log(responses);
  this._photos.push(...responses);
});

forkJoin will initiate all calls for files under 5Mb in size (map & filter handle that), and once all calls are completed, the responses will be added to your array.

UPDATE To ensure your calls are in sequence, opt for using concat instead:

concat(...Array
  .from(files)
  .map(file => file.size < 5000000 && this.asyncFunc(file) || undefined)
  .filter(value => !!value)
).subscribe((...responses) => {
  this._photos.push(...responses);
  console.log(this.photos);
});

Answer №2

Can you please give this solution a try?

Transforming the array of files to a new array of results asynchronously using the flatMap function and async/await syntax. Each file is processed by the asyncFunc function and the result is pushed into the _photos array.

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

What is the equivalent of Typescript's Uint8Array and Uint16Array in Python?

new Uint8Array(new Uint16Array([64]).buffer) How can I achieve a similar data structure in pure Python? What is the equivalent of Uint8Array/Uint16Array? I am extracting a buffer from a Uint16Array type here and converting it to a Uint8Array, but I am un ...

Implement type declarations for a React JS form validation schema

I encountered the following scenario: interface FORM<P> { onSubmit: (d: P) => void; schema?: yup.SchemaOf<P>; } This is an example of my onSubmit function: const onSubmit = (d: { firstName: string; lastName: string }) => { conso ...

how can I display the JSON description based on the corresponding ID using Ionic 3

I have a JSON file containing: [{ "id": "1", "title": "Abba Father (1)", "description": "Abba Abba Father." }, { "id": "2", "title": "Abba Father, Let me be (2)", "description": "Abba Father, Let me be (2) we are the clay." }, { ...

Having trouble clicking on a button with Protractor because the button text is located within a child span element

Having trouble clicking a button with protractor. The DOM structure is displayed in the image above. Here are some of the locators I've attempted to use: element(by.xpath("(//div[@class='mat-drawer-backdrop ng-star-inserted'])//a followin ...

Issue with TypeScript version 4.2.1 - The Array.some() method does not support a function that returns a boolean

I encountered a TypeScript error that goes as follows: https://i.sstatic.net/RoGER.png The complete error message reads: Supplied parameters do not match any signature of call target: parameter type mismatch. > Parameter 'Predicate' should ...

Guide on optimizing Angular CLI production builds with gzip compression

When I build my angular project using ng build --environment=${environment}, the bundle files created are quite large. The version of "@angular/compiler-cli": "^4.0.0" does not generate .gz files in the dist folder. Is there a simple way to create .gz bu ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Enclose the type definition for a function from a third-party library

I prefer to utilize Typescript for ensuring immutability in my code. Unfortunately, many libraries do not type their exported function parameters as Readonly or DeepReadonly, even if they are not meant to be mutated. This commonly causes issues because a ...

Having issues with TypeScript while using Redux Toolkit along with Next Redux Wrapper?

I have been struggling to find a solution. I have asked multiple questions on different platforms but haven't received any helpful answers. Can someone please assist me? Your help is greatly needed and appreciated. Please take some time out of your bu ...

Implementing dynamic form fields in Angular 2 to efficiently store user input in a database

Currently, I am involved in a project using Angular 2. The task is to include fields with data from the database (specifically rows with the field value 'test8'). If users want to add new fields and values, they need to click the "Add new row" bu ...

The View is not reflecting changes in the Variable

Is there a way to disable all the buttons when selectedplace is null in the Dialog, as it currently works when the Dialog first starts but remains activated all the time when the option is changed? I have attempted the following: Customized HTML: ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo: public listUsers(filterSurname?:string):any { if (this.connected) { debug.log(this.db); var results; this.db.collection(' ...

Develop a variety of Jabber client echo bots

Hello Stackoverflow Community, I've been trying different approaches to resolve my issue, but I keep ending up with stack overflow errors. Programming Language: Typescript Main Objective: To create multiple instances of the Client Class that can be ...

TypeScript compilation error - No overload is compatible with this call

Currently, I am working on a project using TypeScript alongside NodeJS and Express. this.app.listen(port, (err: any) => { if (err) { console.log("err", err) } else { console.log(`Server is listing on port ${port}`); } }); The co ...

An error arises in Typescript when the reducer state does not update upon clicking. The error message indicates that the properties 'state' and 'dispatch' are not recognized on the type 'UserContextType | null'

Having recently delved into typescript with react, I've encountered some issues. Despite trying various solutions, the state doesn't seem to work properly and I keep getting a typescript error stating: Property 'state and dispatch' does ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

Improve your code by avoiding the use of multiple ngIf statements

Looking for ways to shorten my code for better readability. I have multiple ngIf statements with various conditions for numbering lists (e.g., 1, 1.1, 1.1.1) Here is a snippet of the code from my template: <span *ngIf="...">{{...}}.</span> .. ...

Error: Could not locate module: 'path' in ' ode_modulessource-map-support' - npm

During the migration process from Angular 5 to Angular 7, I encountered a couple of errors such as map and forkJoin being deprecated. Thankfully, those issues were resolved. However, there is still one lingering error that crops up when running ng serve. ...