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

Utilizing personalized Angular component as a feature within OpenLayer map

I am exploring the possibility of integrating my own component as a zoom control for an OpenLayers map. I came across some helpful information here, indicating that it can be achieved by creating specific HTML elements. However, I already have a pre-existi ...

Unable to Navigate with NativeScript

Having recently ventured into Angular and NativeScript, I am currently working on creating an app. While I have successfully built my first page, I am facing some challenges with routing to my signInComponent. This is the setup that I currently have: In a ...

"Using MongoDB with Node.js to handle asynchronous operations with promises, using

Is there a way to rewrite this code using .then and .fail instead? In the script below, the database connection is retrieved with db.get() in line 1 and stored as "db" for use in db.collection('......).find({}). Essentially, db.get() serves as an ali ...

What is the best way to convert the text on a button into another language?

Currently, I am facing an issue with translating a button using Angular. The translation appears to be outside of the button in question. Additionally, there is another problem that I have encountered. For reference, here is a sample: https://i.stack.i ...

Running your Angular application on a Node server: Step-by-step guide

I am looking to deploy my application using express on a Node server. This is the content of my server.js file: var express = require('express'); var path = require('path'); var app = express(); app.get('/', (req, res) => ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

Embedding a TypeScript React component within another one

Currently, I'm facing an issue with nesting a TypeScript React component within another one, as it's causing type errors. The problem seems to be that all props need to be added to the parent interface? Is there a way to handle this situation wi ...

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

Configuring the CKEditor edit functionality in Angular 2

If you're looking to configure your CKEditor in Angular2, you can refer to the documentation provided by CKEditor here. Here is an example of how I am using it in my HTML: <ckeditor [(ngModel)]="ckeditorContent" [config]="{toolbar : 'Bas ...

Utilizing emotion with MUI v5 for dynamic theming

After upgrading MUI from v4 to v5, I'm facing some difficulties grasping the concept of theming with the various solutions available. I find it challenging to determine when to use MUI theming/styling components and when to opt for emotion ones. Whil ...

Tips on incorporating esbuild extensions in the template.yaml file of AWS SAM

Currently, my TypeScript Lambda functions are managed using the AWS Serverless Application Model (SAM), and I rely on esbuild for the build process. I'm interested in incorporating esbuild plugins into my build process to enable support for TypeScrip ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Setting up Cypress.config file for SQL database testing with Cypress

Currently, I am looking to experiment with SQL databases. I have SqlWorkbench installed and have mysql added in my package file. However, I encountered an issue while attempting to run Cypress as SyntaxError: Unexpected token 'export' The probl ...

Binary encounters an issue: Error - Module failed to self-register

Binary file saved to the specified directory Caching binary for future use [email protected] during postinstall node script execution. The system attempted to locate the relevant binary but encountered an error: Module did not self-register. This iss ...

Angular Email Validator triggers inconsistently based on conditions

I am working on validating email addresses only when they are provided. My approach involves subscribing to the valueChanges function and applying validators based on certain conditions. However, I have encountered an issue where the validator does not tri ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...