Mastering the art of chaining promises effectively within a forEach loop in JavaScript

During my work with mongo, I encountered a need to execute an async call for each item within a loop. My goal is to carry out another command only when all promises within the loop have been fulfilled. However, currently it seems that the promises in the loop are being resolved after the code specified in the 'then' block following the loop.

I am aiming for the sequence to be:

Loop iteration promises then additional code

Instead of the current order which is:

Further code Looped promises

MongoClient.connect(connecturl)
.then((client) => {
  databases.forEach((val) => {
    val.collection.forEach((valcol) => {
      client.db(val.databasename).stats() //(This is the async call)
      .then((stats) => {
        //Perform actions here based on the collection stats
      })
    })
  })
})
.then(() => {
  //Execute this section once all tasks above this point are completed
})
.catch((error) => {
}

Your help in resolving this issue would be greatly appreciated.

Answer №1

When working with iterables such as arrays, you have the option to use async/await in order to iterate through them using a for/of loop:

    MongoClient.connect(connecturl).then(async (client) => {
        for (let db of databases) {
            for (let valcol of db.collection) {
                let stats = await client.db(db.databasename).stats();
                // Perform operations based on the stats of each collection
            }
        }
    }).then(() => {
        // Execute this code after all tasks above are completed
    }).catch((error) => {
        // Handle any errors that may arise
    })

If you prefer sticking to your current .forEach() approach, you can still achieve the desired outcome by running tasks in parallel and utilizing Promise.all() to track their completion:

MongoClient.connect(connecturl).then((client) => {
    let promises = [];
    databases.forEach((val) => {
        val.collection.forEach((valcol) => {
            let p = client.db(val.databasename).stats().then((stats) => {
                // Work with the statistics of each collection here
            });
            promises.push(p);
        }); 
    });
    return Promise.all(promises);
}).then(() => {
    // Perform actions after everything above has been executed
}).catch((error) => {
    // Handle any errors within this block
});

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

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

The issue lies in the constructor not properly updating the property when referencing "this

Apologies for the confusion with the question title, I am still new to using constructors in JavaScript and struggling with how to properly phrase it. Here is the issue I am facing: I am implementing a Builder pattern (using a constructor) to create an ob ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...

What causes the selection of the menu item $invalid to always return as true?

I have an HTML form with a select menu: <form name="form"> <select name="gender" ng-model="model" ng-required="true" ng-model-options="{ updateOn: 'mousedown blur'}"> <option value="" disabled>--Select--< ...

Can the arrangement of icons/buttons on the JW Player control bar be customized?

I am trying to customize the skin of my JWplayer like this: This is my current progress: I have been researching how to rearrange the order of icon / button on the controlbar. According to the jwplayer documentation, the buttons on the controlbar are div ...

Switch up Three.js texture in externally imported Collada model

Currently, I am using the three.js collada loader to bring in an .dae file that includes a texture (.png) image. The challenge I am facing involves replacing this original .png file with a new texture generated from a canvas element and saved in .png forma ...

React encountered a 400 error when attempting to call a function in node.js

While attempting to call a registration endpoint from a React front-end to a Node.js back-end using Axios, I encountered a 400 error: http://localhost:9000/user/register 400 (Bad Request) Here is my code: /* React component for user registration */ impo ...

Retrieve the class name based on the ID of the final appearance of the div using jQuery

<div class='user user1' id='newuser'></div> <div class='user user2' id='newuser'></div> <div class='user user3' id='newuser'></div> To retrieve the class name ...

Disabling a second drop down field upon selecting an option in the first drop down

I have implemented a feature in my code where selecting an option from drop down one automatically updates drop down two. However, I now want to restrict users from manually editing drop down two. You can check out the live example here. var objArray = ...

Do not delay, MongoJS function is ready to go!

I have a function set up in my Express JS endpoint that uses 'await' to retrieve data from a Mongo DB using Mongo JS. Function:- async function getIntroducer(company){ const intro = await dbIntro.collection('introducers').findOne({c ...

The database is showing the update, however, it is not being retrieved in

Brand new to this platform. Currently utilizing PHP, MySQL, JavaScript, and executing JQUERY and AJAX functions. I have an anchor link that triggers a function. The function clears out a DIV tag and then populates (via SELECT query) a table with rows in ...

Verifying conditions in an AJAX-based upload system using JavaScript

Recently, I was working on implementing a JavaScript/AJAX upload system with a progress indicator based on a tutorial. The process went smoothly, and I even managed to include a CSS progress bar for visual representation. However, I encountered a hurdle th ...

Transforming a canvas into a div element

Hey there, I'm looking to swap out one canvas for another but I'm not sure how it will look on the browser. Any help would be greatly appreciated. <div id="juego"> <canvas width="203" height="256" id="1" class="bloque"></canvas& ...

What is the best method for delivering a JavaScript string as an XML document to a user in Express.js?

I am facing a challenge where I cannot save a string buffer as a file and send it, due to my use of elastic beanstalk. However, I only have a string and I want the user to be able to download it as an XML document. router.get('/', (req, res) =&g ...

Guide on resolving the issue with CORS policy

I am currently working on a project that involves using socket.io. However, I have encountered an error in the browser console: Access to XMLHttpRequest at 'https://back.escootrent.com/socket.io/?EIO=4&transport=polling&t=OwxDnkM' from ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

Unable to access filteredItems from custom popup in uib-typeahead retrieval process

Issue with Retrieving Filtered Items from ng-repeat in Controller using $scope Despite trying to fetch filtered items from ng-repeat, the value of $scope.filteredItems appears as undefined when I log it to the console. I attempted to implement the solutio ...

Exploring objects as strings to retrieve data with Javascript

In a scenario where I receive an object of varying length that I do not control, I am required to extract specific data from it. The response I receive is in the form of a formatted string: { "questionId": 18196101, "externalQuestionId": "bcc38f7 ...

Using React js to retrieve data from multidimensional arrays

I am currently working on interacting with a json api. Initially, I was able to access the api and display the first array using the map method. However, I am facing difficulty in accessing anything beyond that initial array. { "client_id": 1, "client_nam ...