如何等待一行代码完成执行,然后继续执行函数中的下一行? javascript/nodejs

时间:2021-04-02 17:23:29

标签: javascript node.js

当我使用 for 循环为 items 中的每个项目调用 fetchLowestBin() 时,一切都很好,直到它到达 db.all()。我希望能够等待该代码片段完成,然后在完成后运行 console.log(itemData)。现在,当我尝试运行它时,它甚至会在开始打印 rows.forEach() 中的内容之前打印出 undefined。我更像是 JavaScript/nodejs 的初学者,对糟糕的代码感到抱歉。

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)
}

0 个答案:

没有答案