Delay the execution until all promises inside the for loop are resolved in Angular 7 using Typescript

I am currently working on a project using Angular 7. I have a function that contains a promise which saves the result in an array as shown below:

appendImage(item){

this.imageCompress.compressFile(item, 50, 50).then(
  result => {
    this.compressedImages.push(result);
    return this.compressedImages;
  });

}

Now, I am calling this function/promise from another function that includes a for loop:

async compressFiles() {

if(this.elementsSelected.length > 0){
 for(let i = 0; i < this.elementsSelected.length; i++){
   let actual = this.elementsSelected[i].src;
   let res = await this.appendImage(actual);
   console.log(res);
 }

  return this.compressedImages;

}else{
  console.warn("No Images Selected");
}

}

My goal is to return the updated array once all promises are resolved. While printing the array directly within the appendImage() function shows it as expected, when I log res inside the loop, I get undefined. What could be causing this issue?

Answer №1

In order to properly wait for your function to complete, you must return the promise.

appendImage(item){

this.imageCompress.compressFile(item, 50, 50).then(
  result => {
    this.compressedImages.push(result);
    return this.compressedImages;
  });
}

should be

appendImage(item){
// This is a promise that needs to be returned in order to use await
return this.imageCompress.compressFile(item, 50, 50).then(
  result => {
    this.compressedImages.push(result);
    return this.compressedImages;
  });
}

Answer №2

The function appendImage does not return properly.

Consider implementing it with the use of an asynchronous function as shown below:

async appendImage(item) {
    const result = await this.imageCompress.compressFile(item, 50, 50);
    this.compressedImages.push(result);
    return this.compressedImages;
}

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

Verify the dates in various formats

I need to create a function that compares two different models. One model is from the initial state of a form, retrieved from a backend service as a date object. The other model is after conversion in the front end. function findDateDifferences(obj1, ...

Issues encountered while accessing REST in Angular 6 due to Access-Control-Allow-Origin restrictions

I am currently facing an issue with loading data from a REST source into my Angular 6 app using http: HttpClient from '@angular/common/http'. When I try to call the app in the browser using ng serve --open, it seems like CORS is causing a problem ...

Transform the property of type any/unknown into a specific generic type T within the map

Suppose I start with... type TypeNonGeneric = { prop1: any, prop2: string }; How do I transform it into... type TypeGeneric<T> = { prop1: T, prop2: string }; I have reviewed the documentation and it appears that I need to create a new generic type ...

Error occurs when trying to open a modal popup within a component due to changes in expression

In my application, I am facing an issue where I have a parent component passing HTML content to a child common component using @ViewChild(). However, when the Child component loads up a popup, the console throws the following error: "ExpressionChangedAft ...

Leveraging Observables in an Angular 2 component to broadcast data to multiple components

Is it possible to utilize Observables in components and which other components can subscribe to them? BugListComponent - The component is injected in the boot.ts file where all services are loaded (where bootstrap is located) import {Subject, BehaviorSub ...

The Vue and Typescript webpage is not appearing in the GAS sidemenu template

I am tasked with developing an application for Google Sides using Vue + Typescript to enhance its functionality with an extra menu feature. You can find a sample without Typescript here. The result is visible in this screenshot: https://gyazo.com/ed417ddd1 ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Angular 10 - unable to bind 'formGroup' as it is not recognized as a valid property of 'form'

In my existing Angular application, I need to implement routing and a login page as the functionality expands. To integrate routing, I have included the following code: app.module.ts // Importing various modules @NgModule({ declarations: [ App ...

The installation process for Angular 4 on npm seems to be never-ending

Recently, I've been encountering difficulties while attempting to install the latest version of Angular 4. Despite upgrading my Node to 6.11.2 and npm to 3.10.10, the global installation of angular-cli is proving to be a time-consuming task with no su ...

Fixing the issue of the Put method not successfully updating MongoDB when using Angular7 with NodeJS on the

Currently, I am facing an issue with my Angular7 application that is connected to NodeJS and MongoDB on the backend. After testing the put method using Postman, it seemed to work perfectly. However, the problem seems to be within the Angular service compon ...

Executing the function in Ionic 4 when the events are absent

In my Ionic 4 multilingual app, I am fetching data from an API based on the selected language. I have set up an event for this purpose, but I face an issue when the event value does not exist - in such cases, I want to run a default function. Below is the ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Choose between using Angular with either PHP and Python or with Django and Python in PHP

For my graduation project, I have developed the frontend using Angular and created a machine learning system with Python. Now, I need to integrate these two components by writing a Web API for Angular using Django, even though I have no prior experience wi ...

Creating a sticky header for a MatTable in Angular with horizontal scrolling

Having an issue with merging Sticky Column and horizontal scrolling. Check out this example (it's in Angular 8 but I'm using Angular 10). Link to Example The base example has sticky headers, so when you scroll the entire page, the headers stay ...

"Encountering the error message "Uncaught TypeError: $(...).summernote is not a function" while working with

I've encountered an issue while trying to implement summernote into my Angular app. I keep receiving the error message "$(...).summernote is not a function" and it seems like summernote is not loading properly on the page. I'm unsure of what step ...

Is there a way to navigate to a specific component selector within an ngFor loop?

I have a scenario where I have multiple components running inside *ngFor on the same page. My goal is to create button links at the top of the page that, when clicked, will scroll to the corresponding component on the page. Below are the code snippets tha ...

Creating a helper function for initiating and ending loading using Angular2's Observable forkJoin

I have a question regarding the forkjoin method in Angular. My main concern is writing a helper function that can handle multiple observables. This helper function should display a spinner service before subscribing to the observables and then hide the spi ...

Modifying the color of a div element solely through CSS styling

I am currently working with a set of buttons, available at this link. While browsing through this helpful post, I encountered an issue. Whenever I click on another element, the orange color of my button disappears. How can I maintain the orange color on t ...

Mastering the art of Typescript typing

I am attempting to start the REST server for an Aries agent as outlined here: import { startServer } from '@aries-framework/rest' import { Agent } from '@aries-framework/core' import { agentDependencies } from '@aries-framework/nod ...