The issue with the .map function in Node.js causing the Express server to prematurely return the response object

I am currently working on creating a customized POST function for an express application in Node.js, inspired by Django's built-in REST methods. This function involves checking the mongo database for valid foreign keys and duplicates. The code snippet below demonstrates how the function makes initial calls to mongo to verify incoming foreign keys against the appropriate tables/collections.

However, I have encountered an issue with the response functionality within the native .map function causing an early return, while still executing the subsequent functions. Here is the problematic code:

const db = require(`../../models`)

const findInDB_by_id = async params => {

  console.log(`querying db`)

  const records = await Promise.all(Object.keys(params).map(function(table){
    return db[table].find({
      _id: {
        $in: params[table]._ids
      }
    })
  }))
  console.log('done querying the db')

  // process records further
  return records
}

// execute findIndDB_by_id using await and perform other operations
// eventually return the response object

Below are the server logs:

querying db
POST <route> <status code> 49.810 ms - 9 // <- expected response
done querying the db
... other stuff

Modifying the map function to not return anything results in skipping the database query and delaying the express response object. By removing the 'return' command as shown below:

const records = await Promise.all(Object.keys(params).map(function(table){
    db[table].find({ // removing the `return`
      _id: {
        $in: params[table]._ids
      }
    })
  }))

The revised server logs indicate:

querying db
done querying the db
... other stuff
POST <route> <status code> 49.810 ms - 9 // <-expected response

This change, however, results in an empty query response since the modified function does not construct the query properly. I also noticed this behavior when trying arrow functions of the format .map(table => (...)).

If you have any insights, explanations, or suggestions regarding this behavior, please share them!

Answer №1

Your initial code is functioning correctly with the expected logs.

All functions using async will return a promise, including findInDB_by_id(). The promise is returned once an await is encountered in the function and the calling code must use await or .then() to access the resolved value from the promise.

When you use return someValue within the function, someValue becomes the resolved value of the promise, allowing the calling code to be notified through await or .then() when the final result is ready.

await only pauses execution of the current async function and does not block the caller at all. The caller still needs to handle the promise returned by the async function.


The updated version of your code executes database queries without control or error handling, often known as "fire and forget". Your code continues running while disregarding any activities in the database queries. This approach is unlikely to be correct, unless specifically needed for certain scenarios. It's advisable to at least log errors in such cases, especially since you are expecting results from the queries.

Answer №2

Consider implementing a solution where the code executes the async function when it encounters it.

let promises = []
Object.keys(data).forEach(function(table){
    promises.push(db[table].find({
        _id: {
            $in: data[table]._ids
        }
    }))
})

let [results] = await Promise.all(promises)

If you prefer to stick with the map method, you can do so like this:

await Promise.all(Object.keys(data).map(async function(table){
    return await db[table].find({ 
        _id: {
          $in: data[table]._ids
        }
    })
})
)

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

Setting custom headers for an HTML document in Playwright involves configuring the necessary HTTP headers to achieve

I'm looking to customize headers in Playwright specifically for an HTML document for unique identification purposes. While browserContext.setExtraHTTPHeaders and page.setExtraHTTPHeaders can set headers for all requests on a page, I am seeking a way ...

What is the best way to pass and save information across different routes in Express using Node.js?

Let's delve into the specific functionalities I envision for my server. Essentially, my project involves user registration and login processes. The URLs for these routes are as follows - localhost:3000/login and localhost:3000/register Upon successf ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Is there a way for me to divide the data in a JSON file and display user tags in place of their IDs?

Looking to create a list admins command for a bot, I'm facing challenges in converting user ids to tags within the command. Take a look at what I have accomplished so far: const { MessageEmbed } = require('discord.js'); const { readFileSync, ...

Learn how to generate dynamic routes in Node.js using Express, such as my.app.com/ghi5938

One feature of my web application is allowing users to upload images. I'm interested in creating dynamic routes that lead them directly to the uploaded photos on my server. However, I haven't been able to find a clear answer on how to accomplish ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

I am encountering an issue where the node app is unable to run the application on the specified port. Can anyone provide an explanation for this?

Struggling with creating an API to generate random names using Node and Express, but encountering issues running the Node app. ...

When executing the command "npm," a message pops up that says "Error: Module 'inherits' not found."

module.js:340 throw err; ^ Error: Module 'inherits' not found at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380: ...

Transferring information from a React Native app to a Node.js server using Express

Looking for advice on transferring data between React Native and Node.js (Express)? I'm currently developing an app using React Native and Node.js with Express, but struggling to establish communication for data exchange. Any tips would be greatly ap ...

Transforming an object into an interface in TypeScript

Recently, I have started learning Typescript and am currently working on a project where I am building a REST API. In this project, I have defined a specific model for my request payload. However, even after typecasting, the type of 'resObj' rem ...

How can I dynamically insert various FormGroup instances into a FormArray in Angular?

I am looking to dynamically populate the order array with multiple dishes. Each dish will be stored as a FormGroup in the form, such as pizza, salad, drink, or any other type of dish. Prior to adding any items, the form structure should resemble this: this ...

I am eager to launch my Node.js Server on Azure App Services

While attempting to deploy my node.js server on Azure using app service, I consistently encounter various errors. The issues range from the build command being unavailable in the configuration to difficulties fetching content. It has become quite frustrati ...

403 Forbidden - PUT https://registry.npmjs.org/shah - Access Denied: You are not authorized to release the package "shah". Please ensure you are logged in with the appropriate credentials

Currently in the process of developing a reactjs component library for npm. I've followed all the necessary steps, but encountering an issue when trying to publish via npm. Despite spending over an hour searching on Google, I haven't been able t ...

I possess a collection of server-side questions and answers. How can I display them one by one in an EJS template upon clicking?

Here is the path I have chosen: app.get('/test', (req,res)=>{ res.render('index.ejs',{qData: [{Q1},{Q2},...]}); }) Is there a way to display this qData sequentially on the client side with each click? Imagine I have two buttons la ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

Using Node.js in combination with Express to render various views

Is there a way to send two consecutive ejs pages to the client with this code snippet: app.post('/', function(req,res) { res.render('yourDemandIsBeingProceed.ejs'); //some code which may take some time (such as running an external ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Is there a way to automatically redirect the server URL when a file is modified?

I am currently experimenting with a function that is supposed to only display a message in the console without redirecting the actual URL of my server when a file is changed. watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watche ...

Leveraging npm packages in Meteor's Angular 1.3 framework

Although it may sound like a silly question, I am still confused. It has been said that Meteor has native support for npm modules in version 1.3. I am currently using Meteor with Angular integration. From the tutorial, it appears that using npm modules sh ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...