2

I am new to nodejs and facing an issue with sqlite select query

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(). In current scenario my parse returns immediately. Any help is appreciated.

2 Answers 2

1

Add an anonymous function to your db.each function:

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. 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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to await a function to finish at node.js you have to use Promises , try the code below :

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

            }
        });
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.