Executing the next function after promise() is not functioning properly in pure JavaScript

I'm completely new to Javascript development.

CURRENT PROJECT - At the moment, I am immersed in developing a web chatbot application.

AN ISSUE - I am encountering difficulties using the promise() function to execute more than one function sequentially.

SOURCE CODE -

var messages = [
  `Hello there!`,
  `Just wanted to let you know that I'm throwing a birthday party this Sunday at my place.`,
  `It would mean a lot if you could make it.`,
];

chatWindow = document.querySelector(".message-day");


const startChat = () => {
  return new Promise(function (resolve, reject) {
    messages.forEach((message) => {
      setTimeout(() => {
        chatWindow.innerHTML += `
        <div class="message">
            <div class="message-wrapper">
                <div class="message-content">
                 <h6 class="text-dark">Karan</h6>
                 <span>${message}</span>
                 </div>
            </div>
            <div class="message-options">
                 <div class="avatar avatar-sm"><img alt="" src="./assets/media/avatar/6.png"></div>
                  <span class="message-date">9:12am</span> 
            </div>
        </div> `;
      }, 2000);
    });
    resolve();
  });
};

startChat().then(() => {
  console.log("2nd Function Executed");
});

You can check out the code live here as well.

How can I ensure that the 2nd function runs only after the completion of the startChat() function?

Answer №1

Currently you are returning 1 promise for 3 operations, but it appears that all 3 operations should be asynchronous. To achieve this, you will need to return a promise for each async operation.

You may want to consider something like the following:

const messages = [
  `Hello there!`,
  `I'm throwing a party this weekend at my place to celebrate my birthday`,
  `It would mean a lot if you could join me`,
];

const chatBox = document.querySelector(".message-box");

const initiateChat = () => messages.map(
    // Returns an array of promises wrapping
    // each message as a promise
    (message, index) => new Promise(resolve => {
        setTimeout(() => {
            chatBox.innerHTML += `
            <div class="chat-message">
                <div class="message-content">
                    <p>${message}</p>
                </div>
            </div>`;
            resolve(message);
        }, 2000 * index);
    })
);

Promise.all(initiateChat())
    .then(args => {
        // args will contain the same strings as in 'messages'
        console.log("Completed Functions", args);
    });

If you wish to execute a callback function before or after each message is displayed, I recommend passing the callback as an argument to initiateChat and calling it when necessary.

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

Is it possible to transform an array into a JSON file and securely store/upload it in an AWS S3 bucket?

Recently, I started exploring aws and its capabilities. Currently, my focus is on developing a web application that allows users to input text in two separate fields. Subsequently, this text will be converted into a Json file and stored in the S3 bucket. ...

Merging a prop of array type in a Vue component

I'm encountering an issue in my component where using the splice function on an array prop does not trigger the $emit event. Can anyone provide some insight into why this might be happening? The removeItem method is called by clicking a button. View ...

Enhancing Textures in Three.js: Methods for Gradually Improving Resolution

I am currently working on a Three.js chart that displays multiple images on a 2D plane. At the moment, each individual image is a 32px by 32px segment of larger 2048px by 2048px image atlas files. I intend to enlarge these individual images when users zoo ...

Convert epoch time to HHMM format using JavaScript

I have a specific variable that stores epoch time data. My goal is to showcase the time information in HHMM format. Below you can find the code I am currently using; function convertEpochTimeToDateObj(epoch_time) { var utcSeconds = epoch_time; va ...

Vanishing HTML upon initial entry to the site using Gatsby and Material UI exclusively in live deployment

I run a blog using Gatsby that includes Material UI components to fetch markdown files through GraphQL. During development, everything operates smoothly. However, in production (after running gatsby build && gatsby serve), the HTML doesn't di ...

Having trouble displaying the time in the middle square when pressing TouchableOpacity in React Native?

Having trouble pressing the TouchableOpacity button as it's not responding, and even after pressing it, I need to access the time picker to select a specific time to display inside the square view in the center. Any suggestions on how to resolve this ...

What external libraries does Angular 4 utilize during execution, aside from RxJS?

Angular 4 relies on RxJS types in its public API and also internally depends on RxJS. It would be beneficial to explore if Angular utilizes other external packages for certain functionalities, allowing us to incorporate them into our own projects. This ap ...

Utilizing AngularJS to create an auto complete feature integrated with a SQL Server database

I have a SQL database table with columns as follows: Row1 Row2 Row3 Id Country 1 1a 1b 34 Europe 2 2a 2b 45 US 3 3a 4d 5g Australia I am currently working on implementing an autocomplete feature ...

Verify if the React component is empty

Within my react component, there's a class or component that contains a specific variable. Below is the relevant code snippet: import React from 'react'; export class Header extends React.Component { constructor() { super(); thi ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

What is the method to process a JSON path containing a special character like "@"?

I'm attempting to retrieve JSON data from an API with the following structure. My current approach involves using JavaScript. The code snippet I have utilized is displayed below. <p>"stations": [</p> <p id="data"></p> ...

Getting rid of an Ajax loader graphic after a period of time

After a button is clicked, I have an ajax loader that appears and here is the code snippet: jQuery(document).ready(function($) { $('#form').on('submit', function() { $('#submit').css('display', 'bl ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

Guide to displaying query results separately on a single webpage

On my page, I have two distinct sections: 1) A list of regular questions; 2) A top-voted list of popular questions Both of these sections rely on calls to the same backend API, with the only difference being an additional parameter passed for the popular ...

How can I convert a button to a link within an HTML table?

I have a question regarding buttons in my HTML table. Is it possible that upon clicking a button, the link button changes to "Un-Extend," and then switching back to the previous button when clicked again? How can I achieve this functionality? https://i.sst ...

Is it possible for Javascript to malfunction on ajax-generated code?

Currently, I am utilizing the jQuery form plugin for file uploads. This plugin employs a hidden iframe to upload files without causing page refreshes. All functionalities are working smoothly except for the fact that the JavaScript is not functioning on th ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

The content of the snackbar message remains static and does not update dynamically

I am attempting to modify some data within a snackbar message, but the message does not seem to update. Here is a brief example of what I am trying to accomplish: https://stackblitz.com/edit/angular-snackbar-qvxipb?file=app%2Fapp.component.html Desired ...

Having trouble populating Extjs Grid with JSON data

In this simple grid, I am attempting to display three columns - Subject ID, Subject Name, and Subject Short Name by obtaining JSON data. The data is stored in a variable called myData in JSON format, which has been received from the server. Despite pasting ...

Extracting image tooltip data through web scraping

There is a unique feature on my website where intriguing information is revealed when I hover my mouse over specific parts of an image. I am interested in extracting this information into a structured format, like so: Zurich, 2000 and more Hinwil, 1400 to ...