2016-12-15 83 views
1

我試圖開發一個連接到Firebase的NodeJS應用程序。我可以成功連接,但我無法知道如何管理then調用中的範圍。NodeJS/Firebase承諾中的範圍

我使用的是6.9.2的NodeJS

我的測試實施看起來是這樣的:

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接受兩個回調,每個回調有一個參數。檢查語法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方法返回一個承諾,所以你可以在外面等待:

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