Why does this asynchronous function initially return nothing, only to suddenly return all results on subsequent tries?

My current task involves inserting data into my database within a map loop. To ensure that the loop completes before proceeding, I am utilizing an async function to store all results in the variable "practicasAgregadas."

This is how I invoke the function:

insertarPracticas(turno_id, req.body.lista_codigos_practicas, queryInsertarPracticas)
  .then(result => {
    res.status(200).json({
      "Practicas Agregadas": result
    })
  })

This is the function itself:

async function insertarPracticas(turno_id, req, queryInsertarPracticas) {
  const res = await Promise.all(req.map(r => {
    connection.query(
      queryInsertarPracticas, [turno_id, r], (error2, row2) => {
        if (error2) {
          console.log("Error al insertar turno detalle (prácticas): " + r + " " + error2);
          practicasNoAgregadas += r + "-";
        } else {
          console.log("Turnos detalle agregados " + r);
          practicasAgregadas += r + "-";
          console.log("practicas " + practicasAgregadas);
        }
      });
    return practicasAgregadas;
  })
  )

  console.log("en async " + res[0]);
  return res;
}

The initial attempt yields an empty result:

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

Here is the corresponding console output:

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

Upon a second attempt, it does return a result, but with three repetitive entries:

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

Accompanied by the following console output:

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

Answer №1

Many modern JS libraries that utilize async functions will typically return a promise, however, they may not do so if a callback is provided.

Assuming that the connection.query indeed returns a promise, the code snippet below should achieve what you are aiming for:

async function insertPractices(turn_id, req, queryInsertPractices) {
    const res = await Promise.all(
        req.map(async (r) => {
            try {
                const row2 = await connection.query(queryInsertPractices, [
                    turn_id, r
                ]);
                console.log("Added practice turns: " + r);
                addedPractices += r + "-";
                console.log("practices " + addedPractices);
            } catch (e) {
                console.log(
                    "Error inserting practice turn: " +
                        r + " " + error2
                );
                unaddedPractices += r + "-";
            }
            return addedPractices;
        })
    );

    console.log("in async " + res[0]);
    return res;
}

Remember to avoid using a callback, as this may imply to the library that you do not want a promise returned.

If the library has not been updated in a while, you may need to promisify the query function.

In Node.js, there is a handy utility called promisify https://nodejs.org/api/util.html#utilpromisifyoriginal that can simplify this process.

For example:

const conQuery = util.promisify(connection.query);
const row2 = await conQuery(queryInsertPractices....

If the callback does not follow the format (error, result), you may need to use a Promise constructor. However, based on your code (error2, row2) =>, this should not be necessary.

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

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Using the componentDidMount() method for server-side rendering

Struggling to optimize the performance of my webpage by server-side rendering, I've encountered an issue where the componentDidMount() lifecycle method of my page's components is not being called. Take a look at my primary template file: import ...

Hover state remains persistent even after modal window is activated in outouchend

One of the buttons on my website has a hover effect that changes its opacity. This button is used to share information on Facebook. It's a simple feature to implement. Here is the CSS code: .social_vk, .social_fb { height: 38px; obj ...

Is it possible to assign numerical values to attributes in HTML code?

I'm unsure about something - is it possible to set an attribute value as a number? For example: <div data-check="1"></div> Is this the correct way to do it or not? I've heard conflicting opinions, with some people saying you shouldn ...

Node.js and its Synchronous HTTP requests

In my system, I have three key components named A, B and C. The workflow involves A sending an HTTP request to B, which in turn sends another HTTP request to C. Upon receiving the response content from C, B sends it back to A as an HTTP response. The func ...

Creating stunning 3D animations using Canvas

I am knowledgeable about Canvas 2D context, but I would like to create a 3D animation similar to this example. Would using the Three.js library be the most suitable option for this type of animation? Any recommendations for tutorials or documentation tha ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

Check through an array for any updates whenever a function is called and my react state is altered

I am currently working on a project related to playlists. My goal is to display the image attached to each song whenever that song is clicked from the playlist. Here is the code I have so far... const Component = () => { const value = useContext(DataC ...

Utilizing nested v-for in Vue.js with lodash's groupBy function

When fetching data from a database, I am using lodash groupby to group my data like so: var vm = this axios.get(this.buildURL()) .then(function(response) { Vue.set(vm.$data, 'model', response.data.model) vm.groupData = _.groupBy(vm.model ...

Create a random number within a specified range using a different number in JavaScript

I am looking for a unique function that can generate a number within a specified range, based on a provided number. An example of the function would be: function getNumber(minimum, maximum, number) { ... } If I were to input: getNumber(0, 3, 12837623); ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Node.js/Express.js is throwing an error: 'undefined is not a function'

I recently started using 'express-namespace' to organize my routing in a cleaner way. Below is the snippet of code I have implemented. .. 9 var controllers = require('./controllers'); 10 require('express-namespace'); .. 46 ...

Enhanced Slider Display featuring Multiple Posts for Improved Performance

My Sample Page features a slider that displays over 200 posts, each containing 5 images. However, the slider loads all the images at once, causing my page speed to be very slow. I am looking for an optimized way to display the slider without compromising l ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

Keystrokes may not consistently register in Firefox

I created a compact web application where users can interact by clicking on a button to trigger a modal dialog. Within this dialog, users have the ability to choose from various options. To enhance user experience, I implemented the utilization of the jQue ...

Implementing Autocomplete search with jQuery Chosen plugin - a step-by-step guide

CSS <select class="custom" id="company_hub" name="company_hub" style="width: 400px; display: none;"> <option>-Select Item-</option> </select> https://i.sstatic.net/x4YtN.png I attempted the following method but it was unsucces ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Updating the value of the variable using ng-submit

My application displays Quantity: {{num}}. The default value is set to 3 in the scope. The objective is to click on: <form ng-submit="addContact()"> <input class="btn-primary" type="submit" value="Add Contact"> </form> and to up ...

What is preventing this from being passed to the subsequent component in ReactJS?

I am trying to get the Portfolio class to utilize the this.prompt method from the Title Bar class. Despite extensive research, I have not been able to find a definitive solution for this yet. Currently, my screen is just blank. Below is the content of my ...

Encountering an EJS error stating SyntaxError: a closing parenthesis is missing after the argument list in the file path C:Userscomputer pointDesktopproject2viewshome.ejs

Struggling to retrieve data from app.js through ejs and encountering an error. Pursuing a degree in Computer Science <%- include('header'); -%> <h1><%= foo%></h1> <p class = "home-content">It is a fact that readers ...