Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
want to make an asynchronous function that stores data from a sql database in an array

I am currently working on a node backend and would like to store data asynchronously from a sql database. In the first step I store the data from the database in an array and in the second step I want to output the array in the console. The problem is that the array is empty every time I output it outside the fetchProducts function. When I output the array inside the function, the entries are correct.

How can I make the function asynchronous so that the console output is only made after all entries in the array have been saved?

let products = [];

async function fetchProducts () {

    
    db.get(`SELECT * FROM products ORDER BY id DESC LIMIT 0, 1`,(err, row) => {
        let maxId = row.id;

        for(let i=1; i<=maxId; i++){
            db.get(`SELECT * FROM products where id = '${i}'`,(err, row)=>{
                let product = {
                    id: row.id,
                    name: row.name,
                    describtion: row.describtion,
                    price: row.price
                };
                products.push(product);

            });
        }
   
    })     
}

async function start (){
    await fetchProducts()
    console.log(products);
}

start();
about 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda