0

When I call fetchLowestBin() with a for loop for each item in items, everything is fine until it gets to db.all(). I want to be able to wait for that snippet of code to finish, and then run console.log(itemData) after it's done. Right now when I try running it, it will print out undefined before it even starts to print what's in the rows.forEach(). I'm more of a beginner with JavaScript/nodejs, so sorry for the terrible code.

let db = new sqlite3.Database('./db/ahdata.db', (err) => {
    if (err) {
        console.error(err.message)
    }
    console.log(chalk.bgGreenBright('SUCCESS') + chalk.greenBright(' Connected to database.'))
    db.run('CREATE TABLE IF NOT EXISTS auctions (auction_uuid TEXT,formatted_uuid TEXT,player_uuid TEXT,item_name TEXT,item_lore TEXT,price INTEGER,start_time INTEGER,end_time INTEGER,catagory TEXT,rarity TEXT,bin INTEGER);')
})


function someFunction() {
    [...]
    items = ['Hyperion', 'Aspect of the Dragons']
    for (i in items) {
        item = items[i]
        fetchLowestBin(item)
    }
}


function fetchLowestBin(item) {
    itemData = []
    db.all(`SELECT * FROM auctions WHERE item_name LIKE "%${item}%" ORDER BY price`, (error, rows) => {
        rows.forEach((row) => {
            if (row.bin != 1) {
                return;
            }
            itemData.push(row);
            console.log(row.formatted_uuid, timeConverter(row.end_time), row.price, row.item_name);
        });
    })
    console.log(itemData)
}
afps
  • 1
  • 2
  • 1
    What type of object does `db.all` return? Chances are this is a promise, and you could probably call `.then` on it. Are you using Node SQLite? – Hanlet Escaño Apr 02 '21 at 17:27
  • 1
    If it's not a promise, you'll need to promisify it manually or move `itemData` into the callback. – ggorlen Apr 02 '21 at 17:30
  • Yeah, I'm using a SQLite3 database with nodejs. – afps Apr 02 '21 at 17:30
  • After reading the documentation for `db.all` I see that you are already inside the callback function (this occurs after the query runs). So you should be able to `console.log(itemData)` at the end of your callback – Hanlet Escaño Apr 02 '21 at 17:31
  • It will be best if you avoid the loop and instead only call db.all once – Nicolas I Apr 02 '21 at 17:33
  • @NicolasI it seems he only needs the rows with bin == 1, which he could probably include in his query btw, and then just return db.all like you indicate. – Hanlet Escaño Apr 02 '21 at 17:35

0 Answers0