2016-12-15 3 views
1

Firebase에 연결하는 NodeJS 앱을 개발하려고합니다. 성공적으로 연결할 수 있지만 then 호출 범위를 관리하는 방법을 파악할 수 없습니다.NodeJS/Firebase 약속의 범위

내가 사용하고 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은 각 인수 하나에 두 개의 콜백을 허용합니다. 구문 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를 반환하므로 외부를 기다릴 수 있습니다.