【问题标题】:SELECT query synchronous with nodejs and sqlite3SELECT 查询与 nodejs 和 sqlite3 同步
【发布时间】:2017-04-25 23:51:08
【问题描述】:

我是 nodejs 新手,遇到了 sqlite 选择查询问题

下面是我的代码。

function parse(topic, msg, name) {

    item = get_obj(tbl_name, handle, JSON.stringify(arg))

    // get item from database
    return [handle, arg, item, action];
}


function get_obj(tbl_name, handle, obj_str) {

    let dbname = "test.sql";
    let query, ret;
    let my_obj = {};
    let db = new sql.Database(dbname);
    let str = "'" + obj_str + "'";
    query = "SELECT handle from " + tbl_name + " where object=" + str;
    db.serialize(function(ret) {
    let ret1 = db.each(query, function(err, row, ret) {
        if (err) {
            console.log("No records found");
        } else {
            if (row.handle == handle) {
                ret = JSON.parse(obj_str);
            }
        }
    });
    });
    }

我希望我的解析应该等到我完成 get_obj()。在当前情况下,我的解析立即返回。任何帮助表示赞赏。

【问题讨论】:

    标签: node.js select asynchronous sqlite


    【解决方案1】:

    如果你想在 node.js 中等待一个函数完成,你必须使用 Promises,试试下面的代码:

    async function parse(topic, msg, name) {
    
        item = await get_obj(tbl_name, handle, JSON.stringify(arg))
    
        // get item from database
        return [handle, arg, item, action];
    }
    
    
    function get_obj(tbl_name, handle, obj_str) {
        return new Promise(resolve => {
            let dbname = "test.sql";
            let query;
            let db = new sql.Database(dbname);
            query = "SELECT handle from " + tbl_name + " where object=?";
            db.each(query, [obj_str], function (err, row) {
                if (err) {
                    console.log("No records found");
                } else {
                    if (row.handle == handle) {
                        resolve(obj_str);
                    }
    
                }
            });
        });
    }
    

    【讨论】:

      【解决方案2】:

      在你的 db.each 函数中添加一个匿名函数:

      let ret1 = db.each(query, function(err, row, ret) {
              if (err) {
                  console.log("No records found");
              } else {
                  if (row.handle == handle) {
                      ret = JSON.parse(obj_str);
                  }
              }, function (err, rows) {             <---- this one
                      parse(topic, msg, name)
                  });
          });
      

      请记住,node.js 函数是异步执行的。因此,您需要有一个回调,该回调将在 db.each() 完成后执行,从而保证回调函数仅在数据库查询完成后执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-22
        • 2023-03-28
        • 2020-11-03
        • 2016-03-22
        • 2021-07-13
        • 2020-05-06
        • 2018-05-23
        • 2018-08-12
        相关资源
        最近更新 更多