Difference Between For Loop and Map Function

I encountered two scenarios while trying to understand what was happening, but the clarity eluded me. I came across information suggesting that when running async calls in a for loop or map, Promise.all must be used. Let me share my experiences:

Initially, I utilized map to update multiple records in my database. It successfully updated some data but not all.

AllAuthToken.map(async singleToken => {
          let deviceIds = uuidv4();
        let newDeviceArray = {
          [deviceIds]: singleToken.deviceToken,
        };
        await AuthToken.updateOne(
          { _id: singleToken._id },
          {
            $set: {
              tokensDeviceArray: [newDeviceArray],
              deviceId: [deviceIds],
            },
          },
          { $new: true }
        );
}

Subsequently, I chose to use a for loop which effectively updated all the data:

  for (let i = 0; i < AllAuthToken.length; i++) {
    let deviceIds = uuidv4();
    let newDeviceArray = {
      [deviceIds]: AllAuthToken[i].deviceToken,
    };
    await AuthToken.updateOne(
      { _id: AllAuthToken[i]._id },
      {
        $set: {
          tokensDeviceArray: [newDeviceArray],
          deviceId: [deviceIds],
        },
      },
      { $new: true }
    );
  }

This discrepancy between the outcomes left me wondering why the first case failed while the second one succeeded.

Answer №1

One of the reasons why .map may not wait for each callback to finish is because it executes them one after the other without any delays. The use of await in an asynchronous function does delay the code that follows, but it does not halt the iteration of .map as it is not within the same scope.

In contrast, a for loop within the same async function as the await will ensure that each iteration waits for the awaited promise to resolve before moving on.

If you want database requests to run "in parallel", where one request can start before another finishes, you can utilize Promise.all like this:

let promises = AllAuthToken.map(singleToken => {
    let deviceIds = uuidv4();
    let newDeviceArray = {
        [deviceIds]: singleToken.deviceToken,
    };
    return AuthToken.updateOne(
        { _id: singleToken._id },
        {
            $set: {
                tokensDeviceArray: [newDeviceArray],
                deviceId: [deviceIds],
            },
        },
        { $new: true }
    );
};

await Promise.all(promises);
/* ... all tasks are completed at this point ... */

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

Validation check: Ensure that the value does not match any other field

Looking for a method to compare two fields and only validate them if they are not equal. This is the approach I've tried, but it's not working: yup .number() .required() .notOneOf( [FormField.houseHoldMembers as any], &ap ...

"Troubleshoot: Issue with React class component's setState not correctly updating

Hey there! I could really use some help with the issue I'm facing: So, I have a React class component that extends React.Component and it has a method that allows me to set its state whenever I want. I understand that passing a prop to the component ...

What is the process for accessing a nested entity list within an object structure?

I've encountered a challenge with storing and retrieving an embedded collection of entities in MongoDB. I have researched the following questions: how to serialize class? and Mongodb saves list of object From what I gathered, in order to save a list ...

When using electron-build, the node-adodb encountered an error stating: 'Failed to spawn C:WINDOWSSysWOW64cscript.exe'

Utilizing node-adodb.js for reading .mdb files with the following code: const db = require('node-adodb') ipcMain.on('query', (e, p) => { if (!p) return appendFileSync('a.log', new Date().getTime() + ' ' + p.t ...

Is there a way to obtain an Instagram login token through AJAX?

I'm encountering issues while trying to receive a token from Instagram. Despite using the following code, I keep running into these errors: SEC7127: CORS request blocked the redirect. SCRIPT7002: XMLHttpRequest: Network Error 0x2ef1, Unable to final ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...

Any ideas on how I can use PHP or JavaScript to repeatedly execute a segment of HTML code?

I recently tried using a for loop and heredoc in PHP with code that looks something like this: $options = ''; for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { $options .= "<option>$Year</option>\n"; } $Select = ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

What is the method for determining someone's age?

I am trying to extract the date from a field called "DatePicker" and then enter that date into the field labeled "NumericTextBox" Thank you <div> <sq8:DatePicker runat="server" ID="dateDatePicker"> <ClientEvents OnDateSelected="get_curr ...

Is it possible in MongoDB to search for an exact data match using the && condition?

I've implemented a sign-in form and stored user information in MongoDB Atlas https://www.mongodb.com/cloud/atlas/. Here is an example of how my data is structured: _id:60a64bee48f6eed16a566cf5 user_name:"test1" user_password:&qu ...

Managing multiple arrays in asynchronous functions in node.js

I am facing an issue with a large array (10K) that I need to split. I tried following this method: and it worked perfectly. However, I now need to pass the separated arrays to a request function and await the response before passing it to savetodb. Could ...

Checking the opacity with an if/else statement, then adding a class without removing the existing class

This function is designed to check the opacity of the header, which fades out as a user scrolls down. If the opacity is less than 1, it disables clickability by adding the class "headerclickoff". However, there seems to be an issue with removing the clas ...

Tips for safely backing up and restoring your MongoDB data stored in a specific Docker volume

My docker image for mongoDB is ready, and now I'm looking to create a script for backing up production data and then restoring it on my local machine. This way, I can set up a development environment that closely resembles the production environment. ...

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

What is the best way to include a css file in a react component directly as raw text?

What am I attempting to achieve? I have a WYSIWYG editor that allows me to create small HTML pages, and then it sends a request to save the page in the backend. Now, I want to include CSS in the request to apply all styles from the parent page (the one co ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Setting filters programmatically in Mui X Data Grid

I am currently working with the MUI Data Grid (pro version) and I am looking to implement checkboxes in the sidebar to filter different columns. Consider three columns: * Column Letters: ['a', 'b', 'c', 'd', etc.] * ...

Please include text beneath the input group addon class

Hey everyone, I'm facing some issues with my layout. Whenever the input fields are empty or null, I encounter errors. I want to ensure that the input text and input group addon have equal heights. Also, upon clicking the submit button, I use jquery/aj ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

Discovering a value within a dictionary list

Having a list of dictionaries like this: l = [{'campo': 'Admin_state', 'valor': 'enable'}, {'campo': 'LinkState', 'valor': 'enable'}, {'campo': 'ONU_in ...