Tips on causing a forEach loop to pause for a regex substitution to occur

I have a project in progress for an email web app where I am working on replacing certain keywords (first name, last name, email) with the actual properties of the user. As of now, I am going through a list of recipients and modifying the email content to make it personalized with the replaced keywords.

One challenge I'm facing: The forEach loop is skipping over the promise that I'm using before I can implement the regex expression to replace the keywords. How can I pause the loop to ensure all keywords are replaced before moving on to the next iteration?

recipientList.forEach(function (recipient) {

        let setContent = new Promise((resolve,reject) =>{

                        personalizedContent = replaceAll(emailContent, '[First Name]', firstName);

                        personalizedContent = replaceAll(emailContent, '[Last Name]', lastName);

                        personalizedContent = replaceAll(emailContent, '[Email]', recipient.EmailAddress.Address);

                        resolve(personalizedContent);
                    })

       setContent.then((personalizedContent)=>{
            var message = {
                "Message": {
                    "Subject": subject,
                    "Body": {
                        "ContentType": "html",
                        "Content": personalizedContent
                    },
                    "ToRecipients": [recipient],
                    "Attachments": []
                },
                "SaveToSentItems": "true"
            };
            postEmail(accessToken,message);
        })


    });

Answer №1

By eliminating the need for Promises in your code, you can easily make the synchronous operation of replaceAll work smoothly without any issues.

 recipientList.forEach(function (recipient) {

      let personalizedContent = replaceAll(emailContent, '[First Name]', firstName);
      personalizedContent = replaceAll(emailContent, '[Last Name]', lastName);
      personalizedContent = replaceAll(emailContent, '[Email]', recipient.EmailAddress.Address);
        var message = {
            "Message": {
                "Subject": subject,
                "Body": {
                    "ContentType": "html",
                    "Content": personalizedContent
                },
                "ToRecipients": [recipient],
                "Attachments": []
            },
            "SaveToSentItems": "true"
        };
        postEmail(accessToken,message);
});

Answer №2

In my opinion, the recipient list should be iterated inside the promise first to replace all contents. Then, in the callback function, iterate through the list again to update the message in the post email.

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

Trouble displaying image due to issues with javascript, html, Angular, and the IMDb API integration

I have been working on displaying images from the IMDb API in my project. Everything works perfectly fine when I test it locally, but once I deploy the project to a server, the images do not load initially. Strangely, if I open the same image in a new tab ...

Trouble with Bootstrap modal implementation when using ajax and looping through data

I am having an issue with using the BS modal to display a form containing a select box and updating records in the database via an ajax call. The trigger button to open the modal consists of <i></i> tags with the same class name, itagbtn, and d ...

Sorting Columns in JQuery Datatables

Encountering an issue with JQuery DataTables (datatables.net) where it takes 2 clicks to sort the columns when there are only 2 rows in the table. The first column sorts on the first click, but subsequent columns require multiple clicks. Despite testing th ...

What could be causing the "Failed prop type" error when dealing with nested cloned children, despite the parent having the correct initial values

Here is a question with two parts: What causes prop types checks to fail in a react-only scenario? How does a material-ui HoC interfere with type checking? When creating UI components, I keep the children unaware of each other by passing props through R ...

Show the chosen choice in a select dropdown with custom text using Angular

I successfully implemented this code snippet to display a dropdown list of countries and their phone codes. However, I encountered an issue where I need to only show the selected option's code without the country name. The first screenshot shows how i ...

Implementing Isotope layout in Reactjs with data-attributes for filtering and sorting content

I am currently working on optimizing the isotope handler within a react component. My goal is to implement filter options such as category[metal] or category[transition], as well as combo filters like category[metal, transition]. Here is the sandbox for t ...

Acquire a structured list of the focus order within the DOM elements

It intrigues me how the DOM is constantly changing. I'm curious if there's an easy way to retrieve a sorted list of focusable elements within the DOM at any moment. This would encompass nodes with a specified tabindex value that isn't -1, as ...

Creating a Node.js application using Express requires careful consideration of file structure and communication methods

Struggling to pass login form credentials to existing JavaScript files for logic and info retrieval. Login page contains a form with POST method. main.js handles the login: main.js module.exports = { returnSessionToken: function(success, error) { ...

Updating the content within a div following the submission of a contact form 7

I'm struggling with my contact form. I want the content of my contact form div to change after clicking submit on the form. I've been searching for a solution, but so far, no luck. Here is what I have: Form (div1) with input fields, acceptance c ...

What is the best way to accomplish a smooth transition of background colors similar to this design

I was browsing different websites and stumbled upon this amazing background color transition that caught my attention. I really liked it and now I want to create something similar on my own website. Despite my best efforts, I haven't been able to achi ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

Using jQuery and AJAX to send a post request in a Razor page and automatically redirect to the view returned by a MVC Action (similar to submitting

I send a json array to the MVC Action using either JQuery or Ajax, and the Action processes the request correctly. However, when the MVC Action returns a View, I am unsure of how to redirect to this View or replace the body with it. Overall, everything se ...

Is it time to ditch Internet Explorer for EDGE?

Have you ever noticed that when attempting to access the stackoverflow website on Internet Explorer, the tab mysteriously closes and Microsoft Edge opens with stackoverflow loaded? What is the secret behind this strange phenomenon on stackoverflow's ...

Simple steps to change the appearance of the delete button from an ajax button to an html button

I need help transitioning the delete button from an ajax button to an html button in my code. Currently, the delete button functions using ajax/javascript and when clicked, a modal window pops up asking for confirmation before deleting the vote. However, ...

Building a time series collection in MongoDB with Node.js

Are there any npm packages available for creating mongodb time series collections using node.js? I did not find any documentation related to this in the mongoose npm package. ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Getting an error message like "npm ERR! code ENOTFOUND" when trying to install Angular CLI using the command "

Currently, I am eager to learn Angular and have already installed Node version 18.13.0. However, when attempting to install Angular CLI using the command npm install -g @angular/cli, I encountered an issue: npm ERR! code ENOTFOUND' 'npm ERR! sys ...

What could be the reason for a querySelector returning null in a Nextjs/React application even after the document has been fully loaded?

I am currently utilizing the Observer API to track changes. My objective is to locate the div element with the id of plTable, but it keeps returning as null. I initially suspected that this was due to the fact that the document had not finished loading, ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...