首页 > 解决方案 > 如何检查 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

标签: firebasereact-nativereturngoogle-cloud-firestore

解决方案


您的函数 renderFollowIcon 总是在 Firestore 中完成任何工作之前立即返回。这是因为 Firestore API 是异步的,并返回一个表示工作何时最终完成的承诺。您需要使用 Promise 来查找任何查询的结果。

您不能只从异步回调中返回一个值。您可能应该改为向 renderFollowIcon 的调用者返回一个承诺,让他们知道您在该函数中执行的任何异步工作的结果。


推荐阅读