Ivan Bertola
Ivan Bertola

Reputation: 261

Synchronous MySQL query with NodeJS and KnexJS

I'm new with NodeJs so I'm stuck with its async behavior, in particular with queries to a MySQL database based on the KnexJS module

Here is the function with the queries:

var getNotes = function(owner) {
        if(owner !== undefined) {
            knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId').then(function(result) {
                console.log(result);
                return result;
            });
        }
        else {
            knex.table('tblnotes').where('public',1).select('noteId').then(function(result) {
                console.log(result);
                return result;
            });
        }
}

But when I use it

var query = getNotes(user.username);
console.log("authenticated");
console.log(query);
console.log("--------------------------------------");
return res.render('authindex.ejs', {title : "Index", user : user,data : query});

and I log the result I have:

authenticated
undefined
--------------------------------------
[ { noteId: 1 } ]

Upvotes: 0

Views: 1790

Answers (1)

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

Solution 1: Use callbacks

var getNotes = function(owner, callback) {
    if(owner !== undefined) {
        knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId').then(function(result) {
            console.log(result);
            callback(result);
        });
    }
    else {
        knex.table('tblnotes').where('public',1).select('noteId').then(function(result) {
            console.log(result);
            callback(result);
        });
    }
}

And use it in routes as following

getNotes(user.username, function(result){
   console.log("authenticated");
   console.log(result);
   console.log("--------------------------------------");
   return res.render('authindex.ejs', {title : "Index", user : user,data : result});
});

Solution 2: Use promises

var getNotes = function(owner) {
    if(owner !== undefined) {
        return knex.table('tblnotes').where('public',1).orWhere({ownerName : owner}).select('noteId');
    }
    else {
        return knex.table('tblnotes').where('public',1).select('noteId');
    }
}

And use it in routes as following:

getNotes(user.username).then(function(result){
   console.log("authenticated");
   console.log(result);
   console.log("--------------------------------------");
   return res.render('authindex.ejs', {title : "Index", user : user,data : result});
});

Upvotes: 1

Related Questions