2016-12-15 22 views
1

Firebaseに接続するNodeJSアプリを開発しようとしています。私は正常に接続することができますが、私はthenコールのスコープを管理する方法を理解することができません。NodeJS/Firebase約束の範囲

I使っていNodeJS 6.9.2

私のテストの実装は次のようになります。

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(); 
.... 

任意のアイデアは、私はそれをどのように管理することができますか?

答えて

1

渡されたコールバックは別のコンテキストから非同期に呼び出されているため、thisはインスタンス化されたオブジェクトに対応していません。

ES6 arrow functionsを使用すると、矢印機能が独自のthisコンテキストを作成しないため、オブジェクトのコンテキストを維持できます。ところで

は、あなたがthen方法で使用している構文はthenは一つの引数それぞれ1と2つのコールバックを受け入れ、正しくありません。構文hereを確認してください。 thenの前にcatchが必要ではないと私は思っています。それを最後に置く方が意味があります。

それはこのようなものになるだろう。一方

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

loginメソッドが非同期操作を行っているようですので、あなたはそれがあなたのコードで終了するのを待つことをお勧めします。私はloginメソッドをPromiseを返すようにして、あなたが外を待つことができるようにします: