使用NodeJS和KnexJS进行同步MySQL查询

时间:2016-06-11 15:35:35

标签: mysql node.js database knex.js

我是NodeJ的新手,所以我一直坚持其异步行为,特别是基于KnexJS模块查询MySQL数据库

以下是查询功能:

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

但是当我使用它时

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

我记录了我的结果:

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

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​:使用回调

    def __delitem__(self, idx):
        """Implements `del self[idx]`"""
        nidx = self._normalize_idx(idx)
        currNode = self.head.next
        if nidx >= len(self):
            raise IndexError
        for i in range(nidx+1, len(self)):
            self[i-1] = self[i]
        del self[len(self)-1]

并在路线中使用它如下

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

解决方案2 :使用承诺

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

并在路线中使用它如下:

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