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

Using JavaScript, you can easily insert the desired text into a TextBox within an Asp.net web application

Is there a way to utilize JavaScript code to automatically insert a specific word into a TextBox when an ImageButton is clicked? The TextBox may already contain some text before the desired word is inserted. Although I have successfully implemented this ...

What are the steps to integrate MaterializeCss into Vue.js?

I prefer not to utilize Vue-Material or Vuetify. My choice is Materialize. Here's what I do: npm install materialize-css@next In my main.js file, where I define my new Vue App, I import Materialize like this: import 'materialize-css' Th ...

Displaying content generated by Html.Raw in MVC4 using JavaScript and AJAX is causing displacement of content within the <a> tags in the HTML

My project includes a feature where emails sent to a specific address are parsed, with attachments saved to the network and metadata stored in a database. If the serial number of a finished good matches the one included in the email, a note is generated an ...

What is the best way to access elements and attributes from a specific JSON file?

Is there a way to access each property within the JSON data provided? Additionally, I am interested in filtering specific objects based on their IDs. How can this be achieved using the array.filter method in JavaScript? { "records": [ ...

Link specifically for the ADFS 2.0 single sign-on application

I've been conducting research on both Google and Stackoverflow but haven't been able to find a solution to my problem. Within my ADFS portal, there are 5 different services that can be selected. I'm trying to determine how I can generate a ...

The Glyphicon icon fails to appear on the initial page load and only shows up after refreshing the

I have been utilizing bootstrap.min.css from bootstrap v3.3.5 which I downloaded from http://getbootstrap.com and used it locally. However, I encountered an issue with glyphicons when running it on IE 9 and above. The glyphicon icon disappears on the first ...

Do not allow negative values to be displayed in the text box

Plunker I need to restrict negative values from being entered into a text field. If the user tries to input a negative value, I want the text box to remain unchanged. Although I have a directive that prevents negative values from being entered, it seems ...

In the tutorial for creating a basic web application, an issue arises with AWS Lambda stating that it "cannot locate module aws-sdk"

As I embark on my AWS journey, I decided to start from scratch by following the Build a Basic Web Application tutorial. Everything seemed straightforward until I encountered an unexpected error while trying to include the basic aws-sdk module! In Brief: ...

The button text in Bootstrap 5 is black instead of white as shown in their demo

During the installation of Bootstrap 5, I encountered an issue where many of my buttons are displaying a black font instead of the expected white font as shown in the Bootstrap 5 Documentation For instance, the .btn-primary button on the official Bootstra ...

Struggling to incorporate JSON data and javascript functions into an HTML file

I've been struggling to create a feed from a json link and display it in separate divs within an html document. Despite multiple attempts with different approaches for three different newspaper sources, I have not been successful. I'm hoping som ...

What is the best way to transfer a table row from one table to another in AngularJS?

I need assistance with a feature that allows users to move rows between tables by clicking on buttons. When the 'up' button is clicked, the 2nd table row should be moved to the 1st table, and when the 'down' button is clicked, the 1st t ...

Looking for guidance on implementing throttle with the .hover() function in jQuery?

Seeking a way to efficiently throttle a hover function using jQuery. Despite various examples, none seem to work as intended. The use of $.throttle doesn't throw errors but ends up halting the animation completely. Here is the code snippet in question ...

Validation of JSON Failed

Encountered a 400 Bad Request error while attempting to POST an answer using Postman, it appears to be a validator issue. Despite multiple attempts, I have yet to resolve this issue. Below are details of the JSON data being sent in the POST request along w ...

Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original stat ...

Display a portion of the existing URL as a clickable link on the webpage using JavaScript or PHP

If I have a website with the URL and I would like to showcase the image at https://example.com/image.jpg on my site (), what can I do? I attempted the following approach, but it only displays the URL of the image. <p id="image"></p> <scri ...

Validating the userid with jQuery before form submission

Currently, I am working on a form where I need to validate if the userID is already in use before allowing the user to submit it. After some research, I came across a solution on another website. However, when I tried to implement the code, I encountered ...

Obtaining a return value from a function that involves a series of chained Ajax requests in jQuery

I'm facing an issue with my function that involves chained Ajax requests. Function A and B are both Ajax requests, where A runs first and B runs after A returns its data. The problem arises when Function C executes Function B. Upon execution of Funct ...

Avoiding data type conversion in JavaScript/TypeScript

Currently delving into the world of JavaScript, I come from a background of working with statically typed languages. Naturally, I opted to dive into TypeScript instead of starting directly with JS. While TypeScript is great and addresses many issues presen ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

Simulating a mobile device screen size using an embedded iframe

Imagine this scenario: What if instead of adjusting the browser window size to showcase a responsive web design, we could load the site into an IFRAME with the dimensions of a mobile screen. Could this concept actually work? Picture having an IFRAME like ...