The functionality of Mongoose async promise appears to be malfunctioning

Struggling with using async in conjunction with mongoose. Here's my code snippet :

function() {
   SchemaOne.findById(fooIdOne).exec().then( x => {
      // Some initial instructions
      myCollection.foreach( y => {
         SchemaTwo.findById(fooIdTwo).exec().then( z => {
            // Additional instructions
         });
      });
   }).then(() => {
      // Code to run afterwards
   });
}

Desiring the "initial instructions" and "additional instructions" to be completed BEFORE the "code to execute after", but the final "then" does not seem to wait for the additional instructions.

Assistance would be greatly appreciated! Thank you, Kev'.

Answer №1

The forEach function you are using is being executed synchronously, and it seems that you are missing the return of a promise in the then callback.

To fix this issue, make sure to collect all promises generated within the loop and then return a Promise.all containing those promises.

function() {
   SchemaA.findById(barIdOne).exec().then( a => {
      // Perform some initial actions
      let allPromises = [];
      myArray.foreach( b => {
         allPromises.push(SchemaB.findById(barIdTwo).exec().then( c => {
            // Implement additional steps here
         }));
      });
      return Promise.all(allPromises);
   }).then(() => {
      // Code to run afterwards
   });
}

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

"Trying to access the Reducer in a container results in an undefined value

I recently tried adding a new Container to my React App, connected it with Redux, and wanted to test if everything was functioning properly. Unfortunately, when I try to access the reducer using this.props.selection, it returns as undefined. This is puzzli ...

Manipulate numerous documents within MongoDB by updating them with varying data in each

I have a list of unique IDs: idList = ["5ec42446347f396fc3d86a3d", "5ec422d4347f396fc3d86a3c", "5ecefaf0aead3070fbdab7dd"] I want to update the documents that match these IDs with different data in each one: const currentData = await Data.updateMany( ...

Unchecking a box becomes impossible in Rails and Ajax due to boolean constraints

Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like... #app/views/tasks/index.html.erb <%- @tasks.each do |task| %> <div class="task-wrapper"> ...

Automatically select all options in MUI Autocomplete by default

Is there a way to have all the values in the autocomplete drop down automatically selected by default when the page loads? I've been experimenting with this example but haven't found a solution yet. If you know how to achieve this, please share! ...

Converting a Class Component to a Functional Component: Step-by-Step Guide

Recently, I have been transitioning from working on class components to function components in React. However, I am facing some issues with my functional component code after converting it from a class component. In my functional component code, there is ...

Retrieve the version of the MongoDB server using the MongoDB .NET driver

I need assistance with determining the MongoDB version of a connected MongoDB Atlas server using the MongoDB .net driver v2.10. Can anyone guide me on how to retrieve this information, such as checking if it is v4.2.5? Your help is greatly appreciated! ...

Error message: The class heritage events_1.EventEmitter is invalid and cannot be recognized

There seems to be a problem with the [email protected] npm dependency. I am attempting to incorporate mongodb into my Vue.js + Vite + Typescript application, but it crashes and fails to load due to an error originating from mongodb. It appears that th ...

Generating a new array and merging different sets of keys together

Is there a way to modify how items are added to a jQuery array? Here is the current code snippet in use: var sub_updated = []; $('.current-sub-items').each(function() { $(this).find('.prod-select').each(function() { if ($(th ...

What is the best way to organize columns on the front end?

A table needs to be displayed on the front end with the following code snippet: <logic:present name="searchStudent"> <table class=" tblSearchResult" border="1" cellspacing="0" cellpadding="0"&g ...

Unable to access a PHP file within a JavaScript loop

In my HTML document, there is a button with an onclick method inside a JavaScript <script> tag. When this button is clicked, it triggers the deleteRow function, which is responsible for removing a row from a table on the page. Within the deleteRow f ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

Styling HTML elements with CSS to create a full width underline effect

Is there a way to make the underlines/borders full width for each line in a paragraph without adding line breaks? I'm seeking suggestions on how to achieve this. Two potential solutions I've considered are using the tag or creating an image, ...

Enforce linting rules for webpack aliases using ESLint

I am currently working with a webpack configuration file that functions as a factory (react-universally boilerplate). In this setup, I have included an resolve option structured like so: resolve: { // These extensions are attempted when resolving a ...

Waiting for the `page.evaluate()` method in Node.js Puppeteer---Is there a way

I am facing an issue where I need to wait for the scrolling action to finish before resolving. When I placed resolve() inside the page.evaluate() block, I encountered an error stating: (node:22646) UnhandledPromiseRejectionWarning: Error: Evaluation failed ...

Safari and iOS 15 to 14 have rendered the Javascript audio context unusable

Recently, I noticed that the IOS/Safari upgrade has caused some issues with the web audio API. Check out this simple code that used to work on IOS and Safari before the upgrade, but now it doesn't work anymore. Interestingly, it still works on Firefo ...

Leveraging JQueryUI for an audio Seek feature, and dynamically connecting a fresh slider to the <audio> element whenever a song is swapped out

Thanks for taking a look at my question. The code snippet can be found HERE. I'm in the process of creating an audio player to handle multiple songs on a single page using JQueryUI Slider and HTML5 Audio, with one Audio element and several sliders. ...

The code snippet `document.getElementById("<%= errorIcon.ClientID %>");` is returning a null value

I need to set up validation for both the server and client sides on my registration page. I want a JavaScript function to be called when my TextBox control loses focus (onBlur). Code in the aspx page <div id="nameDiv"> <asp:Upd ...

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

Submitting data using AJAX yields results, but the contact form remains untouched

I have created an online quiz using jQuery. My goal is to send the results, along with the user's contact information, to the moderator once they submit it. I have managed to send the result information successfully. However, I am facing an issue whe ...

What is the root cause behind the recurring appearance of this line in Angular/D3.js?

I recently came across an excellent tutorial on integrating the D3.js library with AngularJS by following this link: . The guide provided has been extremely helpful in getting me started (big thanks to Brian!) However, I'm eager to delve deeper into ...