Tips for obtaining the output of an asynchronous function that contains a query within a loop

I am facing an issue where I need to retrieve a value after the completion of a for loop that is nested within an asynchronous function. The loop contains a query that inserts data into a database.

The function seems to be functioning correctly, but when I test it with Postman, the response comes back empty even though the values have been successfully inserted into the database.

This is how I invoke the function:

        insertPractice(turno_id,req.body.practice_codes_list, practiceInsertQuery)
        .then( result=> {
                 res.status(200).json({
                      "Added Practiced": result
                    })
                 }
        )

And here is the implementation of the function:

async function insertPractice(turno_id, req, practiceInsertQuery){
//addedPractices="";
return new Promise((resolve, reject) => {
    for (let i=0; i< req.length; i++){ 
        connection.query(
            practiceInsertQuery, [turno_id, req[i]],(error2, row2) => { 
                if (error2) {
                    console.log("Error inserting practice details:"+req[i] +" "+ error2);             
                    practicesNotAdded += req[i] + "-";                   
                }else{
                    console.log("Practice added""+req[i]);
                    addedPractices += req[i] + "-"; 
                    console.log("practices "+addedPractices);
                }
        });
        console.log("inside for loop "+addedPractices);
    }
    resolve(addedPractices)

    // Or handle error cases
    reject("error");
})

The issue lies in the fact that the function does not wait for the query to complete, even though it successfully inserts values into the database. When testing with Postman, I receive an empty response like this:

https://i.sstatic.net/sKgsW.png

However, the values are indeed inserted into the database. What is the right approach to tackle this problem? I have tried using map instead of a for loop and now experimenting with promises, although unsure if my implementation is correct.

Here is the console output demonstrating that the console.log("inside for loop" + addedPractices) returns empty when there should be some values present:

Answer №1

Regarding the construction of your connection file, I am unsure of the specific method you used. However, it would be beneficial to revise it into an asynchronous function and utilize await when executing the connection.query method.

Answer №2

Once your map is complete, simply add this line of code:

await Promise.all(yourArray);

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

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...

Executing various angular 4 applications simultaneously using a shared Node.js server for rendering purposes

What is the best way to configure index files for both front-end (Angular 4 CLI) and backend (Angular 4 CLI) in order to manage two separate Angular apps? ...

What is the best way to add items to arrays with matching titles?

I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the du ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

How to use Sequelize for aggregating data within nested includes on PostgreSQL

The database I'm working with consists of several tables that are relevant to my project, including users, listings, and reviews. Each user can have multiple listings, while each listing can have multiple reviews. A specific column in the reviews ta ...

How to dynamically alter a PHP variable using a JavaScript button click on the existing webpage

I've spent the last hour scouring stackoverflow for answers to my problem, but trying out solutions has only resulted in errors - perhaps because I'm attempting to implement it on the same page. I've experimented with saving the value to a ...

Tips for concealing lengthy text within a select box and automatically wrapping it when displayed as an option

Is there a way to conceal lengthy text within a select box and display it only when the option is selected? I want to hide long text in a select box options, but have some sort of signal to show that more text is available. Is there a javascript solution ...

Livereload in Gulp fails to automatically restart the server

How can I make my gulp+livereload server automatically restart and update the page when JS files are changed? Below is a snippet from my gulpfile.js: var gulp = require('gulp'), livereload = require('gulp-livereload'), ...

Could someone assist me in resolving the issue of receiving empty emails from my online form submission?

Every day, I receive 6 blank emails from my contact form at the same time. Even though the form on the website is filled out correctly and all the information goes through, I still get these mysterious blank emails. I have implemented validation checks in ...

Node.js Multer encountering undefined req.file issue when handling multiple file uploads

FIXED: ( NO req.file ) ( YES req.files ) My project requires the ability to upload multiple files. If single image uploads are working but multiple image uploads aren't (uploading to files), I need req.file.filename in order to write the image path ...

Is there a common method for generating complex identifiers to be used as the HTML element's id, class, or name attributes

Is there a recommended method for "encoding" complex identifiers such as {Source:"ARCH.1", Code: "456-789.456 A+", SubNumber:##2} to be used in HTML elements' id, class, and name attributes? I could come up with something myself, but perhaps there is ...

How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

Transitioning from traditional Three.js written in vanilla JavaScript to React Three Fiber involves a shift in

I am currently faced with the task of converting a vanilla JS Three.js script to React Three Fiber. import * as THREE from 'three'; let scene, camera, renderer; //Canvas const canvas = document.querySelector('canvas') //Number of lin ...

Credit for the Position swipejs

After integrating a swipeJS photo slideshow into my jQuery mobile application, I encountered an issue. I am trying to create points for counting the pictures similar to what is seen on this page: Although I have added the necessary HTML and CSS code to my ...

Generating new objects from API request in React and aggregating them into a single, comprehensive object

I have developed a program that utilizes Axios to fetch data through API calls. I aim to save the fetched result as an object within my this.state.matrixDictionary variable. However, each time I make another API call, the previous object gets replaced. My ...

Executing code upon the completion of jquery's slideUp() function

Is there a method to trigger the execution of html() only after the completion of slideUp()? <p class="test">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent tortor elit</p> $(".test").slideUp().html(""); I attempted using ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

The specified container is not a valid DOM element

Recently, I decided to implement Redux into my React application. However, as I began setting everything up within my index.js file, I encountered an error message: https://i.sstatic.net/4kL2T.png. After some research, I learned that this error is related ...