SELECT query与nodejs和sqlite3

时间:2016-12-10 17:42:59

标签: node.js select asynchronous sqlite

我是nodejs的新手,面临sqlite select query

的问题

以下是我的代码。

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()。在当前场景中,我的解析立即返回。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分: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);
                }

            }
        });
    });
}

答案 1 :(得分:0)

向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()完成后执行一个回调,从而保证回调函数只在DB查询完成后执行。

相关问题