首页 > 解决方案 > 如何在一个生成函数中使用一个高阶函数的变量?

问题描述

需要使用email = user.emailin newcomment['comments/'+id] = {id,comment,email,date},但我不能使用email = yield user.emailoryield auth.onAuthStateChanged(user => {email = user.email})并且 email 被归为 null in newcomment。我怎么能这样做?

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))
}

}

标签: javascriptreactjsfirebase-realtime-databasereduxredux-saga

解决方案


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

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

推荐阅读