Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!