sqlite 如何在查询块外访问变量?

zazmityj  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(178)

我想在查询外部使用for循环,但它打印为空。

sql = 'SELECT * FROM people';
let currMarker = [];

db.all(sql, [], (err,rows) => {
    if (err) return console.error(err.message);
    
    currMarker = rows;

    for (let i = 0; i < currMarker.length; i++) {
        console.log(currMarker[i].name);
        console.log(currMarker[i].username);
    }
});

我想像这样使用它:

sql = 'SELECT * FROM people';
let currMarker = [];

db.all(sql, [], (err,rows) => {
    if (err) return console.error(err.message);
    
    currMarker = rows;
});

for (let i = 0; i < currMarker.length; i++) {
    console.log(currMarker[i].name);
    console.log(currMarker[i].username);
}
2izufjch

2izufjch1#

这里有一个解决方案。

sql = 'SELECT * FROM people';

let currMarker = [];

const queryFunc = () =>{
    return new Promise((resolve, reject)=>{
        db.all(sql, [], (err,rows) => {
            if (err) return console.error(err.message);
            
            currMarker = rows;
            resolve();
        });
    });
};

queryFunc().then((val)=>{
    for (let i = 0; i < currMarker.length; i++) {
        console.log(currMarker[i].name);
        console.log(currMarker[i].username); 
    }
});

相关问题