What is the best way to implement a Promise Function within a For loop?

Here is a function called sendEmail:

public async sendEmail (log: LogMessage): Promise<void> {
nodemailer.createTestAccount(async () => {
      return ServiceFactory.getSystemService().getNetworkPreferences().then(async (networkPreferences) => {
....

I am looking to incorporate this function into a for loop:

for (const log of logs) {
          const timestamp = moment(log.creationDate)
          const startTime = new Date(Date.now())
          if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            return this.sendEmail(log)
          }
        }

The issue I am facing is that I cannot remove "return this.sendEmail(log)" since the function returns a Promise. However, the loop only runs once with the first log before terminating. How can I make sure the function is executed within the loop?

Answer №1

To efficiently handle multiple promises, store them in an array and create a promise that resolves only when all the sendEmail promises have completed.

sendAll() {
    let allMails: Promise<void>[] = [];
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            allMails.push(this.sendEmail(log));
        }
    }
    return Promise.all(allMails);
}

If you prefer to execute the sendEmail functions sequentially, you can utilize async/await to pause execution until one email is sent before proceeding with the next one:

async sendAll(): Promise<void> {
    for (const log of logs) {
        const timestamp = moment(log.creationDate)
        const startTime = new Date(Date.now())
        if ((timestamp.diff(startTime)) >= rule.miliSecond && category.includes(log.category)) {

            await this.sendEmail(log);
        }
    }
}

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

Switch up the key while iterating through a JSON object

Can you modify the key while iterating through objects using an external variable? Picture it like this: var data = [{ "id": 1, "name": "Simon", "age": 13 }, { "id": 2, "name": "Helga", "age": 18 }, { "id": 3, "name": "Tom ...

Encountering an error when implementing a router object within a TypeScript class in a Node.js environment

I have a Node.js service written in TypeScript. I am currently working on implementing a separate routing layer within the application. In my app.js file, I have the following code: let IndividualRoute= require('./routing/IndividualRoute'); app ...

A destructured object with a Typescript interface

While working on a React / TypeScript project, I encountered an error involving destructuring an object. The issue arises when I try to destructure notificationData within the publish function. An error message stating "Property 'messages' does ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

Steps for specifying the required type of an Object literal in Typescript

Let's analyze a straightforward code snippet interface Foo{ bar:string; idx:number; } const test1:Foo={bar:'name'}; // this is highly recommended as it includes all required fields const test2={bar:'name'} as Foo; // this is ...

The module for the class could not be identified during the ng build process when using the --

Encountering an error when running: ng build --prod However, ng build works without any issues. Despite searching for solutions on Stack Overflow, none of them resolved the problem. Error: ng build --prod Cannot determine the module for class X! ...

What is the best approach for utilizing Inheritance in Models within Angular2 with TypeScript?

Hey there, I am currently dealing with a Model Class Question and a ModelClass TrueFalseQuestion. Here are the fields: question.model.ts export class Question { answerId: number; questionTitle: string; questionDescription: string; } truefals ...

Merging the functions 'plainToClass' and 'validate' into a single generic function in NodeJs

Here's the issue I'm facing: export const RegisterUser = async (request: Request): Promise<[number, UserResponse | { message: any }]> => { let userRequest = plainToClass(UserRequest, request.body); let errors = await validate(u ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

Struggling with setting up a search bar for infinite scrolling content

After dedicating a significant amount of time to solving the puzzle of integrating infinite scroll with a search bar in Angular, I encountered an issue. I am currently using Angular 9 and ngx-infinite-scroll for achieving infinity scrolling functionality. ...

Having trouble retrieving values from radio buttons in Angular 2 forms

Having trouble displaying the values of radio button inputs in Angular 2 forms. ...

Issue: Encounter of "Uncaught (in promise) TypeError" while implementing RiveScript chatbot in Angular

I've been working on integrating a chatbot based on RiveScript into Angular. The chatbot is functioning well - I always see the correct response in the console. Displaying the user's input is also working seamlessly. However, I'm encounterin ...

Introducing the concept of type-specific name inclusion

I am currently developing my Angular app using TypeScript with the goal of preventing redundancy through some form of generic handling. Here is where I am starting: class BaseProvider { api_url = 'http://localhost:80/api/FILL_OUT_PATH/:id&apo ...

What is the reason for a boolean extracted from a union type showing that it is not equivalent to true?

I'm facing a general understanding issue with this problem. While it seems to stem from material-ui, I suspect it's actually more of a typescript issue in general. Despite my attempts, I couldn't replicate the problem with my own types, so I ...

Dependencies exclusively for NPM post-installUnique Rewrite: "N

I have been using git to distribute an internal TypeScript NPM package. To avoid cluttering my repository with build files, I have implemented a postinstall action to build the package upon installation: "postinstall": "tsc -p tsconfig.json& ...

Creating a TypeScript interface where the type of one property is based on the type of another property

One of my Interfaces has the following structure: export enum SortValueType { String = 'string', Number = 'number', Date = 'date', } export interface SortConfig { key: string; direction: SortDirection; type: Sort ...

Visit the map only after the promises have been fulfilled

In my current project, I am utilizing the loadash map function for data structuring. The data retrieved consists of a series of IDs that require querying the database and integrating the results into the map before returning. However, the data is delayed i ...

Display the new data from an array that has been created following a subscription to Angular Firestore

I am struggling to access the content of a variable that holds an array from a Firebase subscription. The issue I am facing is that I am unable to retrieve or access the value I created within the subscription. It seems like I can only use the created valu ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...