The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block.

However, in my code, something appears to be off as it doesn't behave that way:


    var noDupes = false;  // set to true eventually but currently blocking any inserts
    console.log('forEach');
    courses.forEach((course) =>
    {
        const promiseNoDupe = new Promise((resolve, reject) =>
        {
            dbo.collection("courses").findOne({ id: course.id }, (err, result) => 
            {
                if (err) throw err;
                if (result) { console.log('dupe'); return reject('dupe'); }
                console.log('nodupe');
                resolve('nodupe');
            });
        });

        noDupes &= promiseNoDupe.then(() =>
        {
            console.log('true promise');
            return true;
        }).catch(() =>
        {
            console.log('false promise');
            return false;
        });
    });
    console.log('End forEach');

    if (noDupes)
    {
        console.log('Inserting many');
        dbo.collection("courses").insertMany(courses, (err, result)  =>
        {
            if (err) return res.status(400).send(error.details[0].message);
            res.send(courses);
        });   
    }
    else
    {
        console.log('No Dupes allowed');
        res.status(400).send('Inserting duplicate ID not Allowed!');
    }

Console output:


forEach
End forEach
No Dupes allowed
nodupe
true promise
nodupe
true promise

The "End forEach" section runs before the promise is fulfilled and before any internal processing takes place! Consequently, the logic dependent on the promise is being executed prematurely.

I'm uncertain about what's causing this issue, but I am attempting to ensure that all checks within the forEach loop are completed before inserting any new records.

Answer №1

Kudos to charlietfl for guiding me towards utilizing map() and Promise.all().

Check out the revised code below:

    var dupePromises = courses.map((course) => 
    {
        return new Promise((resolve, reject) =>
        {
            dbo.collection("courses").findOne({ id: course.id }, (err, result) => 
            {
                if (err) throw err;
                if (result) return reject(false);
                resolve(true);
            });
        }).then(() =>
        {
            return true;
        }).catch(() =>
        {
            return false;
        });
    });

    Promise.all(dupePromises).then((results) =>
    {
        if (results.every((isnotDupe) => { return isnotDupe /* == true */ }))
        {
            dbo.collection("courses").insertMany(courses, (err, result)  =>
            {
                if (err) return res.status(400).send(error.details[0].message);
                res.send(courses);
            });
        }
        else{
            res.status(400).send('Inserting duplicate ID not Allowed!');        
        }
    });
}

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 grease/tampermonkey (or any other browser extension) to filter out specific characters within webpage elements

Forgive me if my language is not accurate, as I am still learning about programming. The forum that I visit has cluttered the page with unnecessary and glitchy images and text for a promotion. This has made the forum difficult to navigate. I was successful ...

Eliminating rows from a DataTable through an Ajax request

I have a DataTables table from datatables.net with a custom column containing icons for various actions. One of these actions is deleting a row without reloading the data. I'm looking for a built-in function to remove datatable rows locally after dele ...

npm build issues stemming from browserlist configurations

I am encountering an issue with my create-react-app failing to build, showing the following error: ./src/index.css Module build failed: BrowserslistError: Unknown browser query `dead` at Array.forEach (<anonymous>) I have carefully reviewed my ...

What is the process of using AJAX, JavaScript, and HTML to submit data to a remote

I need help with sending data from an HTML page to a server. I have a JSON example below that illustrates what I want to achieve. On my HTML page, I have a question label and four options (A, B, C, D) as radio buttons. After clicking the send button, I ...

How to determine the length of a JavaScript object

Would like help determining the length of the report_data(object) key using the provided code, but it seems to result in a value of 3. a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"} Object {report_freq: "daily", report_ite ...

My backend axios post request is not returning any data to my external API. What could be the issue?

I've encountered an issue where I'm attempting to transmit data from my client-side using an ajax call to my backend axios post request, which is responsible for posting data to an external API URL. Despite receiving a 200 status code, none of th ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

The embedded iframe on YouTube is displaying the incorrect video

I am currently designing a website and I want to feature a video on the homepage. The video is hosted on YouTube and I need to embed it into my website. <html> <iframe width="560" height="315" src="https://www.youtube.com/embed/spPdelVEs_k?rel= ...

Interactive search tool with multiple fields using HTML and JavaScript

I need help developing a search box for structured data, where I want to implement two types of typeahead searches: one for fields and another for values within those fields. The image below illustrates what I am aiming for. My backend systems are all set ...

Making an AJAX request in Javascript to retrieve multiple values using the HTTP method 'GET' from a URL

xmlhttp.open("POST","BAConsultRecordsAJAX.php?q="+str,true); Could this be achieved? xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str+"j="+str2,true); I need to have values stored in both q and j fields. ...

Interactive game created using JavaScript input

I've scoured the internet for guidance on creating a text-based game that utilizes user input, but all I come across are tutorials focusing on button interactions. What I envision is triggering different responses based on specific user inputs. For i ...

"Enhancing User Experience with AngularJS by Dynamically Modifying and Refresh

I'm currently attempting to dynamically add HTML elements using JavaScript with a directive: document.getElementsByClassName("day-grid")[0].innerHTML = "<div ng-uc-day-event></div>"; or var ele = document.createElement("div"); ele.setAttr ...

Increasing the ID of a select input using Jquery

Is there a way to modify the identification of my select field? This select option is dynamically created using PHP. The select input can be accessed through var indirectSelect Despite its simplicity, I am facing difficulty in changing it. I attempted th ...

What is the process for receiving updates while subscribing in ReactReduxContext.Consumer?

I am currently seeking a solution to staying updated on changes to a stored value in the Redux store by subscribing. I have attempted the following method: <ReactReduxContext.Consumer> {({store}) => { console.log('store:& ...

What is the best way to achieve complete code coverage for ajax requests, including success and failure callbacks, using Jasmine and Blanket.js?

Here is a sample code snippet for adding a row: var Utils = {}; Utils.genericAddRowPost = function(url) { return $.post(url); }; Utils.genericAddRow = function(dataSource, url) { genericAddRowPost(url).done(function(data, textStatus, jqXHR) { ...

I'm struggling to understand why the jQuery find() method isn't functioning as expected

UPDATE: In a twist of events not caused by syntax errors, but rather by a loading issue with the html template, it turns out that the checkbox update was happening prematurely. So if you're searching for an element that seems to be missing, it may sim ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Looking to personalize the appearance of an iframe using CSS styling?

I am working with an iframe that generates a form, and I would like to customize the CSS of this form. How can I go about editing the CSS? <div class="quiz-container" style="text-align: center;" data-quiz="#######" data-pr ...

What purpose does the .set() function serve in Node.js with Express?

As I delve into learning Node syntax, there's this particular code snippet that has caught my curiosity. Can you shed some light on its purpose? server.set('views', __dirname); ...

What are the best methods for capturing individual and time-sensitive occurrences within a service?

I am currently working on structuring the events within a service to enable a mechanism for subscribing/unsubscribing listeners when a controller's scope is terminated. Previously, I utilized $rootScope.$on in this manner: if(!$rootScope.$$listeners[& ...