简体   繁体   English

SELECT 查询与 nodejs 和 sqlite3 同步

[英]SELECT query synchronous with nodejs and sqlite3

I am new to nodejs and facing an issue with sqlite select query我是 nodejs 的新手,遇到了 sqlite 选择查询的问题

Below is my code.下面是我的代码。

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

I want my parse should wait till i am done with get_obj().我希望我的解析应该等到我完成 get_obj()。 In current scenario my parse returns immediately.在当前情况下,我的解析立即返回。 Any help is appreciated.任何帮助表示赞赏。

If you want to await a function to finish at node.js you have to use Promises , try the code below :如果你想在 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);
                }

            }
        });
    });
}

Add an anonymous function to your db.each function:向您的 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)
            });
    });

Keep in mind that node.js functions are executed asynchronously.请记住,node.js 函数是异步执行的。 Due to this you need to have a callback that will be executed once the db.each() finishes and thus guaranteeing the callback function will only execute after the DB query has completed.因此,您需要有一个回调,该回调将在 db.each() 完成后执行,从而保证回调函数仅在数据库查询完成后执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM