Executing simultaneous asynchronous queries with Mongoose results in an error: `SyntaxError: Illegal return statement` due to

My goal is to make multiple asynchronous requests to Mongo using Mongoose in parallel. To achieve this, I created a helper function that handles these queries dynamically without knowing the exact number beforehand. While my current implementation works well, I have some reservations about the use of eval in my code. The issue arises when I try to execute the eval(return${returnStr}) statement and it results in a SyntaxError.

const batchRetrieve = async (query, models) => {
  models.forEach((model, i) => {
    eval(`task${i} = ${model}.findOne(query)`);
  });
  let str = [];
  for (let i = 0; i < models.length; i++) {
    str.push(`res${i}: await task${i}`);
  }

  const joinedStr = Array.prototype.join.call(str, ', '); //output is 'res0: await task0, res1: await task1'

  // return { res0: await task0, res1: await task1 }; works fine 
  eval(`return { ${joinedStr} };`);
};

Answer №1

Remember: Avoid using eval whenever possible. Here's a better approach:

const batchProcess = async (data, steps) => {
  const tasks = [];
  steps.forEach(step => {
    tasks.push(step.process(data));
  });

  const outputs = [];
  for (let i = 0; i < steps.length; i++) {
    outputs.push(await tasks[i]);
  }

  return outputs;
};

Answer №2

After changing the eval(return { ${joinedStr} };); to

  return eval(`(async () => {
        return { ${joinedStr} }
    })();`);

The problem I was facing got resolved.

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

Cherrypy/Chrome: Issue with jquery ajax request remaining pending after several successful requests

My current project involves a Cherrypy server that receives a JSON array from a client via AJAX call. The server then manipulates the array and sends it back to the client. However, I've noticed an issue where after a few smooth requests, the next req ...

JQuery restricts input to only allow numbers with a set number of digits, ensuring uniqueness

Can someone assist me in creating a jQuery script that only allows unique numbers with exactly 4 digits in a numeric field? Here is the HTML code: <input type="text" id="registration_number" class="input-sm" name="registration_number" maxlength="6" re ...

JavaScript - Attempting to insert a value into a text field by clicking a button

I am struggling to get my function to properly add the value of the button to the text field when clicked by the user. HTML <form name="testing" action="test.php" method="get">Chords: <textarea name="field"& ...

What is the best way to send props to a styled component without needing to convert them to transient props beforehand

Recently, I designed a custom Text component that accepts several props. These props are then forwarded to the styled component where specific styles are applied. However, I am facing an issue where I do not want these props to be passed down to the DOM, b ...

Initiating change notification when utilizing service communication

So I am facing an issue with two unrelated components where I am attempting to establish communication between them using a service and a BehaviorSubject. Despite successfully exchanging data, calling the service from one component does not trigger change ...

"Curious about the outcome of the upsert operation using the Mongo node driver - was it an insertion

Currently working with the MongoDB native node driver. When performing an upsert like this: collection.update(query, setData, { upsert: true }, callback); Is there a method to determine whether the upsert resulted in an insert or an update? In the Mongo ...

Transfer Parameters from the Screen to the Header Component in React Navigation

I am facing an issue where I am unable to pass a function as parameter to the header component in react-navigation v5. In the code snippet provided below in filtersscreen.js, my intention is to pass savefilters to headerRight which is located in navigatio ...

Utilize jQuery to substitute numbers with strings through replacement

My question pertains to the topic discussed here. I am looking for a more refined jQuery replacement function that can substitute a number with a string. My PHP script returns numbers in the format of 1.27 Based on a specified range, these numbers need ...

Is there a way to order the execution of two functions that each produce promises?

With my code, I first check the status of word.statusId to see if it's dirty. If it is, I update the word and then proceed to update wordForms. If it's clean, I simply update wordForms. I'm looking for advice on whether this is the correct a ...

How can the datetime value of the Apex Charts datapoint be shown in the tooltip?

I'm struggling to find the proper location within the w.globals object to display the x-axis value, which is a datetime, in the tooltip of the datapoint. var chartOptions = { ... xaxis: { type: "datetime" }, tooltip: { x: { format: " ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

Working with attributes in AngularJS directives

Building an overlay (or modal window) in AngularJS has been on my mind, and I've made some progress with the html/css layout. Here's a sneak peek at what it looks like: <section class="calendar"> <a open-overlay="overlay-new-calenda ...

Implementing a design aesthetic to installed React components

After downloading a react multiselect component created by an individual, I installed it using npm install .... and incorporated the component in my react code with <MultiSelect .../>. The dropdown checkbox 'menu' is designed to allow users ...

Error encountered with jQuery XML: 'Access-Control-Allow-Origin' header is not present on the requested resource

For a personal project I'm working on just for fun, I'm trying to read an XML file from , parse the data, and use it to convert currency values. Although my code to read the XML is quite basic, I encountered the following error: XMLHttpRequest ...

Sorting complex strings in Typescript based on the dates contained within them

How can I sort a list of 2 strings with dates inside them so that the earlier one always comes first? The date is always after the second comma. For example, const example = ["AAA,5,2020-09-17T21:14:09.0545516Z", "AAA,0,2020-09-03T20:38:08. ...

Using Vue to dynamically upload multiple files simultaneously

Although this question has been asked frequently, most of the answers do not address a key issue - how to upload multiple images while knowing which image belongs to which data. Attempting to bind v-model to input file doesn't work as expected, and ev ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

Notifier - The Best HTML Notification System for Web Applications

Currently, I am developing a notification system using Play Framework 2.3 (Java) in combination with MySQL. The system is designed to retrieve notifications from a "notifications" table stored in MySQL database. I initially attempted to use AJAX polling ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

jquery method for retrieving default value from dropdown list

When no option is selected from the dropdown list, I require the default value to be used for business logic purposes. ...