javascript - 如何在一个生成函数中使用一个高阶函数的变量?
问题描述
需要使用email = user.email
in newcomment['comments/'+id] = {id,comment,email,date}
,但我不能使用email = yield user.email
oryield 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))
}
}
解决方案
只要您只对用户第一次调用 onAuthStateChanged 回调感兴趣,您只需将其转换为 Promise:
const user = yield new Promise(resolve => {
const unsub = auth.onAuthStateChanged(user => {
if (user) {
resolve(user);
unsub();
}
});
});
推荐阅读
- cmake - 在构建“内部”(非根)项目时也适用的分层 CMake 项目
- ubuntu - 在操作系统升级后运行 cargo build(在一个旧的 Rust 项目上)说我缺少几个系统依赖项。这是正常的吗?
- javascript - 哪些引导 css 和 javascript 文件应该链接到我们的 html 页面?
- python - 使用 Dask Dataframe 附加到 Parquet 文件时出错
- f# - 我不明白这个警告:不应给方法或函数提供显式类型参数
- c# - Get-WindowsOptionalFeature 从 C# 失败
- python - Django:我的对象的列表属性没有保存在函数中
- python - 有没有办法在fortran和python之间传递任意精度数?
- javascript - 如何从 dm 获得用户回复?(不和谐节点 js 机器人)
- loops - 汇编器 x64 NASM。为什么循环对我不起作用?