What is the method to provide function parameters without executing the function?

I'm searching for a solution to obtain a function that requires a parameter without actually invoking the function.

Example of current malfunctioning code:

const _validations = {
  userID: (req) => check('userID').isString().isUUID('4').run(req),
};

async function (req, res, next) {
  const allReqFields = { ...req.body, ...req.params, ...req.query };

  const fieldsFound = [];
  for (let key of Object.keys(allReqFields)) {
    if (_.has(_validations, key)) {
      fieldsFound.push(_validations[key](req));
    }
  }

  await Promise.all(fieldsFound);

  return next();
},
  function (req, res, next) {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
//ALWAYS HITS HERE
      return next();
    }else{}
}

Working code example, but undesired:

const _validations = {
  userID: (req) => check('userID').isString().isUUID('4').run(req),
};

async function (req, res, next) {
  const allReqFields = { ...req.body, ...req.params, ...req.query };

  for (let key of Object.keys(allReqFields)) {
    if (_.has(_validations, key)) {
      await _validations[key](req);
    }
  }


  return next();
},
  function (req, res, next) {
    const errors = validationResult(req);

    if (errors.isEmpty()) {
//Correctly hits here
      return next();
    }else{
//Correctly hits here
    }
}

To provide some context:

The function

(req) => check('userID').isString().isUUID('4').run(req),
returns a promise.

There will be additional keys/values within the _validations object.

Every function within _validations requires req to be passed as an argument.

The ultimate goal is to execute all those asynchronous functions while passing req to them.

The issue I'm currently facing is that

fieldsFound.push(_validations[key](req));
is appending a promise instead of the function for future invocation. As a result, fieldsFound becomes an array of unresolved promises

Any suggestions? Thank you!

Answer №1

const _validations = {
  userID: () => check('userID').isString().isUUID('4')
};

In order to execute the functions, you need to push them into an array without invoking them:

fieldsFound.push(_validations[key]);

To complete the process, execute each function by passing in req and awaiting the returned promises:

await Promise.all(fieldsFound.map(func => func().run(req)));

Answer №2

One approach is to utilize function currying.

In functional programming, we can employ currying to transform a function that accepts multiple arguments into a chain of nested functions. This results in the creation of a new function that anticipates the next argument provided.

To illustrate this concept, modify your function as illustrated below:

const _validations = {
  userID: (req) => () => check('userID').isString().isUUID('4').run(req),
};

This way, you'll be able to call upon the function later when needed.

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

Import and load numerous JSON files into a responsive and visually appealing Bootstrap table

I am new to coding in javascript and I'm seeking assistance in loading multiple JSON files to populate a bootstrap table. Currently, I've managed to create a table by manually combining the content from different files into one variable called l ...

What is the procedure for enabling S3 images or objects to be downloaded exclusively through website requests using pre-signed URLs?

I am facing a serious issue with my AWS S3 bucket setup. I have been using the aws-sdk javascript to upload files to the bucket and providing object links for downloading on my Next.js website. However, I recently realized that the bucket permissions are s ...

What strategies can be used to enhance proficiency with Google Home without solely relying on voice commands?

Just starting out with Google Assistant and I have a question regarding using it with Google Home. Is there a way to enable Google Home to respond without needing voice input? Can I interact with Google Home in any other way besides speaking, and still re ...

Unable to Incorporate WSL Interpreter into Intellij Idea 2018

Struggling to add the WSL node interpreter to my Intellij Idea(2018.2.2) as it can't detect NodeJs(version 12.14.1) installed on WSL2. I have Node installed with NVM on UBUNTU 20.04.1 LTS through Windows Store. Despite trying different methods like r ...

Having trouble with Javascript files failing to load while hosting a website on digital ocean?

Recently, I developed a web application using an express backend and the ejs view engine. Everything works perfectly fine when tested on my local machine. However, I encountered issues when trying to host it on a digitalocean droplet (Ubuntu 22.10 x64). Af ...

Utilize jQuery to track and record AdWords conversions

I have noticed a number of inquiries regarding tracking Adwords conversions with jQuery on this platform. However, it appears that there is no definitive solution yet. My attempt at recording a conversion involves the code below following the submission o ...

The updateOne query in MongoDB is generating duplicate data

Hey developers. Let's dive right in... I'm facing an issue when updating a column in the database. Upon updating, the data in the column seems to be getting multiplied inexplicably even though the duplicated data shares the same _id, which is su ...

Is there a way to trigger a "click" on a webpage without physically clicking? So that I can preview the response message before actually clicking

Is it possible to generate a "mock" request to a server through a website in order to examine the response before sending the actual request? Let me clarify with an example: if I were to click on a button on a website, it displays a certain message. I am ...

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

Having trouble with the installation of packages using the Node Package Manager on Ubuntu

Ubuntu has renamed the NodeJS interpreter name (node) to nodejs due to a conflict with another package. The Debian readme states: The original name for the Node.js interpreter command is "node". In Debian, it was changed to "nodejs". This change was ...

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

Comparing React-Highcharts to regular Highcharts

Despite my efforts to find information on this topic through search engines, I have come up empty. So, I am turning to you with my question. Can someone explain the distinction between these two NPM packages: https://www.npmjs.com/package/highcharts htt ...

How can you retrieve command line variables within your code by utilizing npm script in webpack?

I'm trying to access command line parameters from an npm script in my "constants.js" file. While I have been able to access parameters in the webpack.config.js file using process.env, it seems to be undefined in my app source files. The scenario con ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Transform an HTML table string into JSON format

I discovered a useful library called table to JSON that allows me to convert an HTML Table to JSON using its ID (#testtable in the example below): var table = $('#testtable').tableToJSON(); alert(JSON.stringify(table)); However, I am interested ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

When the mouse hovers over the slider, the final image jumps into view

After successfully building an image slider that displays 2 partial images and 1 full image on hover, I encountered a bug when setting the last image to its full width by default. This caused a temporary gap in the slider as the other images were hovered o ...

The chosen value remains constant even after altering the selected option

I am trying to create a scroll-down bar that allows users to select different options, and once an option is selected, its value should appear in the bar. However, I'm facing an issue where the value does not change according to the selection: const [ ...

What is the best way to eliminate a duplicate item from the shopping cart without actually deleting it?

I developed an e-commerce platform with a cart feature using the context API. However, I encountered an issue where removing one item from the cart also deletes another item if there are two of the same items in the cart. How can this be prevented? Below ...