firebase - 如何检查 Firestore/Firebase 中是否存在文档并将其提供给 var 或返回?
问题描述
我想在 Firestore 中存在文档时渲染图像,但我不知道如何将 .then 函数的值返回到其原始函数并且返回 true 或 false 不起作用。返回值始终为 true。
renderFollowIcon(email){
if(
firebase.firestore().collection("user").doc(this.state.currentUserEmail).collection("follows").doc(email).get()
.then((docSnapshot) => {
if (docSnapshot.exists){
Alert.alert("hi")
return true;
}
Alert.alert("not hi")
return false;
})){
return(
<TouchableOpacity onPress={() => this.unfollow(email)}>
<Image source={require("../assets/unfollow.png")} style={styles.FollowIcon}/>
</TouchableOpacity>
)
}else{
return(
<TouchableOpacity onPress={() => this.follow(email)}>
<Image source={require("../assets/follow.png")} style={styles.FollowIcon}/>
</TouchableOpacity>
)
}
}
这是新代码,但它仍然无法正常工作:
var promise2 = Promise.resolve().then(firebase.firestore().collection("user").doc(this.state.currentUserEmail).collection("follows").doc(email).get()
.then((docSnapshot) => {
if (docSnapshot.exists){
Alert.alert("hi")
return Promise.reject( true );
}else{
Alert.alert("not hi")
return Promise.reject( false );
}
return (check.promise)
}))
@DougStevenson
解决方案
您的函数 renderFollowIcon 总是在 Firestore 中完成任何工作之前立即返回。这是因为 Firestore API 是异步的,并返回一个表示工作何时最终完成的承诺。您需要使用 Promise 来查找任何查询的结果。
您不能只从异步回调中返回一个值。您可能应该改为向 renderFollowIcon 的调用者返回一个承诺,让他们知道您在该函数中执行的任何异步工作的结果。
推荐阅读
- python - 更改组合问题:我找到了这段代码,但我无法理解某些行
- python - 应用返回错误消息的函数:“时间戳”对象不可下标
- javascript - Vaadin 14 Springboot javascript不起作用
- ios - 安装 Cocoapods 时出错:[!] Invalid `Podfile` 文件:未定义的局部变量或方法 `cocoapods' 用于#
- algorithm - 我的递归记忆解决方案的运行时间是多少
- config - Mosquitto Bridge 主题设置忽略模式
- notion-api - 如何从 Notion 中删除表中的一行?
- powerbi - 如何在 Power BI 中的两行计算中添加新列?
- python - 如果字符串中没有空格,如何在字符串中添加空格?
- node.js - 猫鼬不在nodejs中获取数据