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:

Here is the corresponding console output:

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

Accompanied by the following console output:

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

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

Ruby on Rails and JSON: Increment a counter with a button press

How can I update a count on my view without refreshing the page when a button is clicked? application.js $(document).on('ajax:success', '.follow-btn-show', function(e){ let data = e.detail[0]; let $el = $(this); let method = this ...

Responsive left and right image styling in CSS and HTML

I have designed a landing page with fixed left and right images and content in the middle. It looks fine on desktop view, but on mobile view, the images are overlapping the content. How can I resolve this issue? <div class=" ...

Avoiding leaps through the use of dynamic pictures?

Currently, I am implementing the picture element along with srcset to download the same image but in varying resolutions depending on the screen size of the device. The image has a style of max-width: 100%, causing it to shift the content below when downl ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Automatically populating state and city fields with zip code information

Starting out in the world of web development, I encountered a challenge with a registration form I'm constructing for our company. For guidance, I referred to this resource: http://css-tricks.com/using-ziptastic/. This project marks my initial interac ...

Unforeseen behavior in Ajax success callback

My unordered list contains a href link. Initially, only the welcome page is visible on page load. Upon clicking the list for the first time after page load, the desired results are displayed in the corresponding div as expected. The issue arises when swi ...

Ways to move down only one level of an element's children, excluding sub-levels

When implementing this code snippet: jQuery: $(this).next().slideDown() with a selector :$(this).next() HTML: <li class="sub-menu two-level-collapse"> <a href="javascript:void(0);" class="two-level-collapse parent">< ...

Creating a custom filter using Express.js in Node.js to retrieve a specific data set based on user preferences

I recently started working with express js as I am in the process of developing a todo list web application. Following various tutorials, I have successfully implemented basic CRUD operations and created two models. Users - (name, email, password hash, p ...

Delete multiple selected rows from the table

I need help with removing multiple rows from a table. I've tried the code below but it doesn't seem to work. I'm using DataTables v1.10.9. $('#del_Btn').on('click', function () { // 'table' is the instanc ...

Issue with Authenticating Certificates on Express Gateway

I am encountering difficulties with connecting Express Gateway to a backend service using OpenSSL-generated certificates. The log displays the following error whenever the gateway attempts to connect to the service: project_edge_express_1 | 2019-12-03T ...

Tips on refreshing a view in react as data updates

Currently, I am delving into learning a variety of subjects such as Typescript, Express, and my newfound interests in REACT and RXJS. To aid in my studies, I created a Quick-List on Github, but encountered a question... "How can the view in React be upda ...

Generate a list item that is contenteditable and includes a button for deletion placed beside it

I am attempting to create a ul, where each li is set as contenteditable and has a delete button positioned to the left of that li. My initial attempt looked like this: <ul id='list'> <li type='disc' id='li1' cl ...

Nodejs encountering issues with reading data from collection despite having "readWrite" role in Mongodb permissions

I developed an application using Node.js and MongoDB. In MongoDB, I added a new user with the roles specified below: { "_id" : "testdb.testdbuser", "user" : "testdbuser", "db" : "testdb", "roles" : [ { ...

Node.js not functioning properly with post call functionality

Struggling to successfully execute a post call in node js, I am testing it using post but having trouble retrieving data. Here is my node code: exports.login = function( req, res ) { console.log("Params:"+req.body.email); //console.log('email:&ap ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

Unable to use NodeJS await/async within an object

I'm currently developing a validation module using nodeJs and I'm facing difficulties understanding why the async/await feature is not functioning correctly in my current module. Within this module, I need to have multiple exports for validation ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

Display index.html regardless of where it is located

I have a Node.js app using Express and I want the index.html file to be displayed to the user regardless of the URL they are on. For example, if someone goes to http://example.com, they should see the same page as if they went to http://example.com/test. ...