Performing multiple SQL queries in a for loop using Node.js and Express

After submitting a Post form, I receive a req.body containing multiple values in the following format:

console.log(req.body)

{

productid:[1, 2, 3]
qty: [3, 5, 6]

}

I'm trying to implement a for loop to use these values in SQL queries. However, I encounter an issue with the first query, likely due to it being an async await function.

My inquiry pertains to how I can execute multiple SQL queries within a for loop while still utilizing an async await function?

Answer №1

This is how you can achieve it:

for each element in the array, execute an asynchronous query using await

Answer №2

Because I simply performed an update without waiting for a response, there was no need to utilize await/async. The process functioned properly after removing async/await.

Thanks a lot!

Apologies for the unclear inquiry.

Answer №3

If you're looking to run tasks simultaneously, consider creating an array of promises and utilizing Promise.all to ensure all operations are completed efficiently. This approach allows for optimization of your code compared to a sequential execution.

    const tasks = []
    for(let item of list) {
      tasks.push(runTask(item))
    }
    const output = await Promise.all(tasks)
    //Process the results as needed.

Remember to declare your request handling function with the async keyword to successfully execute the code.

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

Tips for utilizing Sass and CSS Modules within create-react-app

I've been using FileName.module.scss to style my react elements like this: // Component styling with SCSS import React from "react"; import Aux from '../../hoc/Aux'; import classes from './Layout.module.scss'; const lay ...

Streaming data from BigQuery to the front-end using Express

Trying to extract a query from BigQuery and stream it to the frontend has been quite a challenge. In the Node.js environment with Express, one would assume it should look something like this: app.get('/endpoint', (req, res) => { bigQuery.cr ...

Do we really need to use redux reducer cases?

Is it really necessary to have reducers in every case, or can actions and effects (ngrx) handle everything instead? For instance, I only have a load and load-success action in my code. I use the 'load' action just for displaying a loading spinne ...

The data in MongoDB is organized using unique identifiers called ObjectId

I am currently working on a MEAN Crud project and encountering some issues. Despite the data being received in the mongodb, it is displaying as an objectId instead of the actual content. You can see this issue in the image below: https://i.stack.imgur.com ...

The HTML image is not updating, the function does not appear to be triggering

My attempt to add a source to an image using JavaScript and some jQuery code I found online isn't working as expected: <html> <head> <script src = "http://www.example.com/images/"> var count=1; var initnumber=100 ...

Maintain the scrollable feature of the element until the final content is reached

I'm struggling to come up with the right keywords to search for my issue. I've tried using Google, but it seems my search terms are not effective. The problem I'm facing involves two relative div elements with dynamic content. This means th ...

The issue at hand is the lack of execution for the Mocha Chai `.end()`

I have encountered an issue while trying to write a Mocha chai test for a Nodejs API that was previously tested using Supertest. Strangely, the test always passes even when I intentionally specify wrong expected parameters. Below is the code snippet of th ...

Tips for Enhancing JavaScript Performance

Is there a way to enhance my JavaScript code like this: $(window).scroll(function() { if ($('#sec1').isVisible()) { $('.js-nav a.m1').addClass('active'); } else { $('.js-nav a.m1').removeClas ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

A step-by-step guide on enhancing error message handling for Reactive forms in Angular

Here is a code snippet that I'm working on: public errorMessages; ngOnInit(): void { this.startErrorMessage(); } private startErrorMessage() { this.errorMessages = maxLength: this.translate.instant(' ...

The selected jQuery plugin is not functioning properly within CodeIgniter framework

I recently downloaded the jQuery Chosen plugin to use the simple "multiselect" version on my website. I followed all the necessary steps and even copied and pasted the code into CodeIgniter. Despite my experience with jQuery, I am facing an issue where the ...

Creating a mind map: A step-by-step guide

I'm currently developing an algorithm to create a mind map. The key focus is on organizing the nodes intelligently to prevent any overlap and ensure a visually pleasing layout. Take a look at this snapshot (from MindNode) as an example: Any suggestio ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...

Enhance User Experience by Implementing Event Listeners for Changing Link Visibility Using mouseover and getElementsBy

I am new to JavaScript and struggling to find a solution. Despite searching online for fixes, none of the solutions I've found seem to work for me. I have spent hours troubleshooting the issue but I must be missing something crucial. Can someone plea ...

Discover the ultimate solution to disable JSHint error in the amazing Webstorm

I am encountering an error with my test files. The error message states: I see an expression instead of an assignment or function call. This error is being generated by the Chai library asserts. Is there a way to disable this warning in Webstorm? It high ...

Making fun of an ES6 class function

Currently, I am in the process of testing an express app, which includes the following files: app.js const express = require('express'); const path = require('path'); const apiRouter = require('./api'); const app = expre ...

Is there a way to activate a function in a sibling component without using Prop Drilling?

Looking at the image, you can see the structure of components I have. <Invoice> <Left></Left> <Right></Right> </Invoice> In the Left component, there is a form, and in the Right component, there is a Submit button l ...

Encountered an error with Winston and Elasticsearch integration: "TypeError: Elasticsearch is not a constructor

I recently implemented winston-elasticsearch on my express server by following the code provided in the documentation var winston = require('winston'); var Elasticsearch = require('winston-elasticsearch'); var esTransportOpts = { le ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...