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();