【问题标题】:react native & firestore - return vs console.logreact native & firestore - 返回 vs console.log
【发布时间】:2021-06-26 18:58:20
【问题描述】:

我遇到了关于 firebase 的小问题,可能还有关于异步函数的问题,我对 react-native 和 js 还是新手,所以我无法自己解决这个错误。

我有以下代码被剪断:

lastmessage = await firebase.firestore().collection("chatrooms").doc(`${chatkeys[i]}`).collection(`${chatkeys[i]}`).orderBy("counter").limit(1).get().then(
    querySnapshot => {
        return querySnapshot.docs.forEach(doc => {
            doc.data().value;
            console.log("console log inside foreach: ", doc.data().value)
        })
    }
)
console.log(lastmessage);

firestore 调用和我的数据库没问题,但问题在于 return 和 console.log() 本身。我的函数内的 console.log() 工作得很好,并在我的控制台内记录了想要的值 - 另一方面,我的函数外的 console.log() 就在下面,不起作用。无论我做什么,它只会让我“不确定”。这是一个大问题,因为我无法在下一部分代码中重用这些检索到的数据。

有人可以告诉我如何解决这个问题吗? I tried already this solution 但它对我的代码没有任何作用,我仍然得到 undefined。

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    Array.forEach 方法不期望闭包返回值。

    您可能正在寻找Array.map

    return querySnapshot.docs.map(doc => {
      ...
    

    接下来,如果您在传递给map(或forEach)的结尾处加上花括号,您还需要在其中包含return 语句。所以:

    return querySnapshot.docs.forEach(doc => {
        return doc.data().value;
    })
    

    或更短:

    return querySnapshot.docs.forEach(doc => doc.data().value);
    

    【讨论】:

    • 还是不好。我的结果不再是未定义的,但现在它变成了: Array [undefined,] 所以基本上我的“未定义”结果被填充到了一个数组中。
    • 我更新了我的答案顶部显示导致该问题的代码中的第二个错误。
    • 这两个语句的组合是我的问题的解决方案,现在一切正常。非常感谢您和来自德国的问候!
    猜你喜欢
    • 2019-07-06
    • 2021-09-29
    • 2023-03-22
    • 2018-12-24
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多