如何在一个生成函数中使用一个高阶函数的变量?

时间:2018-12-27 22:10:17

标签: javascript reactjs firebase-realtime-database redux redux-saga

需要在email = user.email中使用newcomment['comments/'+id] = {id,comment,email,date},但是我不能使用email = yield user.emailyield auth.onAuthStateChanged(user => {email = user.email}),并且电子邮件在newcomment中的属性为null。我该怎么办?

export function* createComments(action){  
let email = null
try{
    auth.onAuthStateChanged(user => {
       email =  user.email
    })
    const id = yield database.ref().child("comments").push().key
    let date = new Date()
    date = yield date.getDate()+"/"+(date.getMonth()+1)+"/"+date.getFullYear()
    const newcomment = {}
    const comment = action.comment
    newcomment['comments/'+id] = {
        id,
        comment,
        email,
        date
    }
    database.ref().update(newcomment)
    yield put(ActionCreator.createCommentsSuccess(newcomment))
}catch({message}){
    yield put(ActionCreator.createCommentsFailure(message))
}

}

1 个答案:

答案 0 :(得分:1)

只要您只对第一次使用用户调用onAuthStateChanged回调感兴趣,您只需将其转换为Promise:

const user = yield new Promise(resolve => {
  const unsub = auth.onAuthStateChanged(user => {
    if (user) {
      resolve(user);
      unsub();
    }
  });
});