繁体   English   中英

如何在不丢失数据库的情况下进行数据库调用?

[英]How to make database call without losing this?

由于数据库本身是一种单独的对象,调用它,我失去了this

var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://localhost:7474');

function MyObject(id){this.id = id}
MyObject.prototype.myQuery = function(){
    db.query('Some Query',{args:params},function(callback){
        //this in here is some neo4j db related object.
        //instead of MyObject
        console.log(this.id); //undefined
    });
}
myObject = new MyObject(9);
myObject.myQuery(); //undefined

任何解决方法,以使数据库调用,还有我this是指从数据库的回调里面原来的预期目标?

在调用之前将其缓存:

MyObject.prototype.myQuery = function(){
    var self = this;
    db.query('QUERY',{args:params},function(callback){
        //If you use self here, it will work.
        console.log(self.id);
    });
}

除了将其保存到一个变量,你也可以绑定this如下所示的功能:

MyObject.prototype.myQuery = function(){
    db.query('Some Query',{args:params},function(callback){
        //this in here is some neo4j db related object.
        //instead of MyObject
        console.log(this.id); //undefined
    }.bind(this));
}

...或使用ES6中的箭头功能,即使这不是一个选择...

您可以保存this调用之前db.query方法,就像这样:

MyObject.prototype.myQuery = function(){
  var thisQuery = this;
  db.query('QUERY',{args:params},function(callback){
    // Now you can use thisQuery to refer to your query object
  }
}

暂无
暂无

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

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