小编bla*_*ght的帖子

如何将 Firebase 返回的数据保存到变量

我正在为我的 React Native 应用程序编码,但无法从firebase.firestore().collection("test_data").doc(ID)循环外的 firebase 返回中获取数据。每当我dataArray在循环后检查变量时,它都是空的。如果我在循环中检查它,数据就在那里。我认为这是一个范围问题,但我只是不明白。我也无法在循环内调用任何用户定义的函数。

    try {
      let dataArray = [];
      // get the document using the user's uid
      firebase.firestore().collection("users").doc(uid).get()
      .then((userDoc) =>{
        // if the document exists loop through the results
        if (userDoc.exists) {
          data = userDoc.data().saved_data; // an array store in firebase

          data.forEach(ID => { // loop through array

            firebase.firestore().collection("test_data").doc(ID).get()
            .then((doc) => {
              dataArray.push(doc.data().test_data);
              console.log(dataArray) // the data shows
            })
              console.log(dataArray) // the data does not show
          })

        }
      })
    } 
    catch (error) { …
Run Code Online (Sandbox Code Playgroud)

javascript firebase reactjs google-cloud-firestore

1
推荐指数
1
解决办法
362
查看次数