2016-12-27 1 views
0

Google OAuth 2를 redux saga와 함께 구현하려고합니다.redux-saga를 통해 Google OAuth 플로우를 처리하는 방법

나는 나의 무용담의 감시자가 다음 googleLogin

function *watchGoogleAuth() { 
    yield *takeLatest(GOOGLE_AUTH, googleLogin) 
} 

function *googleLogin() { 
    const id_token = yield call(GoogleSignIn); 
    console.log(id_token); 
    const response = yield call(HttpHelper, 'google_token', 'POST', id_token, null); 
    console.log(response); 
} 
을 실행 GOOGLE_AUTH 조치에 대해 듣고있다

GoogleSignIn의 구현은 apis.js

export function GoogleSignIn() { 
    const GoogleAuth = window.gapi.auth2.getAuthInstance(); 

    GoogleAuth.signIn({scope: 'profile email'}) 
     .then(
     (res) => { 
      const GoogleUser = GoogleAuth.currentUser.get(); 
      return { 
      id_token: GoogleUser.getAuthResponse().id_token 
      }; 
     }, 
     (err) => { 
      console.log(err) 
     } 
    ) 
} 

에 있지만 사가는 대기하지 않는 것 완료하려면 GoogleSignIn. OAuth 동의 화면이 팝업되면 Saga는 실제 데이터를 반환하겠다는 Google 로그인 약속을 기다리지 않고 console.log을 실행합니다.

이 상황을 처리하는 더 좋은 방법이 있습니까? 감사!

+1

GoogleSignIn 함수는 약속을 반환해야합니다. –

답변

1

@ HenrikR의 답변에서 확장하려면 발전기가 약속을받지 않으면 대기하지 않습니다.

export const GoogleSignIn =() => { 
    const GoogleAuth = window.gapi.auth2.getAuthInstance(); 

    return new Promise((resolve, reject) => { 
    GoogleAuth.signIn({scope: 'profile email'}) 
     .then(
     (res) => { 
      const GoogleUser = GoogleAuth.currentUser.get(); 
      resolve(GoogleUser.getAuthResponse().id_token); 
     }, 
     (err) => { 
      reject(err) 
     } 
    ); 
    }); 
} 

따라서 yield 문을 try/catch로 래핑해야합니다. 단순하고 다소 게으름 :

function *googleLogin() { 
    try { 
    const id_token = yield call(GoogleSignIn); 
    if (id_token) { /* Possibly with more checks and validations */ 
     console.log(id_token); 
     const response = yield call(HttpHelper, 'google_token', 'POST', id_token, null); 
     console.log(response); 
    } 
    } catch (e) { 
    console.log(e); 
    } 
} 
관련 문제