javascript - 如何监听 Javascript 中的变量变化?

标签 javascript asynchronous couchdb node.js

我一直在使用 Node.js 和 CouchDB。我想要做的是在对象中进行 db 调用。这是我现在正在查看的场景:

var foo = new function(){
   this.bar = null;

   var bar;

   calltoDb( ... , function(){

      // what i want to do: 
      // this.bar = dbResponse.bar;

      bar = dbResponse.bar;      

   });

   this.bar = bar;

}

所有这一切的问题在于 CouchDB 回调是异步的,“this.bar”现在在回调函数的范围内,而不是类。有没有人有任何想法来完成我想要的?我不希望有一个处理程序对象必须对对象进行数据库调用,但现在我真的被它异步的问题难住了。

最佳答案

只需保留对 this 的引用即可:

function Foo() {
   var that = this; // get a reference to the current 'this'
   this.bar = null;

   calltoDb( ... , function(){
      that.bar = dbResponse.bar;
      // closure ftw, 'that' still points to the old 'this'
      // even though the function gets called in a different context than 'Foo'
      // 'that' is still in the scope and can therefore be used
   });
};

// this is the correct way to use the new keyword
var myFoo = new Foo(); // create a new instance of 'Foo' and bind it to 'myFoo'

关于javascript - 如何监听 Javascript 中的变量变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3637763/

相关文章:

exception - Haskell (ghc) Control.Exception 中,try 和 catch 的区别

couchdb - 袋 DB : database size

javascript - 区分自定义指令的作用域方法 angularjs

javascript - 从过滤列表中删除时的 ng-repeat 动画

javascript - 如何使用 sequelize.js 查询特定 ID 以便我可以更新它

c# - 如何创建 Azure.AsyncPageable 进行模拟?

javascript - 一个 onComplete 回调用于执行两个函数中的最后一个

python - CouchDB POST 响应(通过 Python 的子进程模块通过 curl 发送)正在丢失(curl 代码 53)。这是为什么?

javascript - Couchdb 从文档中的两个数组发出文档

javascript - 在 React 的模板文字中插入 html 标签