NodeJS / Firebase承诺的范围

我正在尝试开发连接到Firebase的NodeJS应用程序。 我可以连接成功,但我无法想象如何在then调用pipe理范围。

我正在使用NodeJS 6.9.2

我的testing实现如下所示:

 const EventEmitter = require('events'); const fb = require('firebase') class FireGateway extends EventEmitter { constructor() { super(); if ( this.instance ) { return this.instance; } // INIT var fbConfig = { apiKey: "xxxxx", authDomain: "xxxxx.firebaseapp.com", databaseURL: "https://xxxxx.firebaseio.com/" }; fb.initializeApp(fbConfig) this.instance = this; this.testvar = "aaa"; } login() { fb.auth().signInWithEmailAndPassword ("email", "pwd") .catch(function(error) { // Handle Errors here. }).then( function(onresolve, onreject) { if (onresolve) { console.log(this.testvar); // "Cannot read property 'testvar' of undefined" this.emit('loggedin'); // error as well } }) } } module.exports = FireGateway; ------ ... var FireGateway = require('./app/fireGateway'); this.fireGW = new FireGateway(); this.fireGW.login(); .... 

任何想法如何pipe理它?

传递给它的callback是从另一个上下文asynchronous调用的,所以this不对应于实例化的对象。

使用ES6的arrow functions你可以保留你的对象上下文,因为箭头函数不会自己创buildthis上下文。

顺便说一句,在你的方法中使用的语法是不正确的, then接受两个callback每个一个参数。 检查这里的语法。 then在此之前的catch是不必要的,我认为,把它放在最后是更有意义的。

这将是这样的:

 login() { fb.auth().signInWithEmailAndPassword("email", "pwd") .then( (onResolve) => { console.log(this.testvar); this.emit('loggedin'); }, (onReject) = > { // error handling goes here }); } 

另一方面,似乎login方法正在做一个asynchronous操作,所以你可能想等待它完成你的代码。 我会让login方法返回一个承诺,所以你可以在外面等待:

 login() { return fb.auth().signInWithEmailAndPassword("email", "pwd") ... }