Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda