代码之家  ›  专栏  ›  技术社区  ›  Dillgo

sqlite将变量输出到js[duplicate]

  •  0
  • Dillgo  · 技术社区  · 7 年前

    所以我有一个带有SQLite的数据库,我很高兴,但是当我试图将一个值输出到一个局部变量时,我收到了以下错误:

    console.log(UserMurderCoins);
    ReferenceError: UserMurderCoins is not defined
    

    我的代码:

    sql.get(`SELECT * FROM monney WHERE userId ="${message.author.id}"`)
       .then(row => {var UserMurderCoins = row.coins});
    
    console.log(UserMurderCoins);
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Amir Masud Zare Bidaki    7 年前

    正如@Lemix在评论中所说, sql.get 是一个异步函数 console.log 会在完成之前被执行。

    也要注意 scope . var UserMurderCoins then 函数并在范围外访问。因此,即使语句在 sql.get.then .

    你可以运行 控制台.log 内部 然后 函数或全局定义变量,并且只在 然后 功能。


    为了更容易接受承诺,你可以使用 async await 语法。

    我修改了你的代码,做了一些小改动。

    async function f() {
    var UserMurderCoins = (await sql.get(`SELECT * FROM monney WHERE userId ="${message.author.id}"`)).coins;
    
    console.log(UserMurderCoins);
    }
    
    f();
    
    推荐文章