javascript - 循环数据以提取 Firebase 值数组

标签 javascript firebase firebase-realtime-database google-cloud-functions

我有一个包含 N 个路径的数组,用于从 Firebase 数据库中的不同位置检索数据。

searchPaths = ['位置/日期1/imageID', '位置/日期2/imageID2', 位置/日期3/imageID3, ...]

现在,我想循环遍历每个搜索路径并从中提取一个值以保存图像 URL 数组。

    const searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2']
    const imageURLs = []

     for(var Obj in searchPaths) 
    {
        const path = Obj
        admin.database().ref(path).once('value').then(snapshot => 
        { 
        const URL = snapshot.val().fileURL;
        imageURLs.push(URL);
        console.log('ImageURL: ' + URL );
        })
    // here is where it gets sour
    }.then(() => {
        console.log("All image URL's" + imageURLs")
    }

所以,我的问题是,当我们现在从每个引用中提取了所需的数据时,如何返回 promise ?是否有 Promise.all 类型?它去哪儿了?

最佳答案

您可以使用 for 循环创建一个 Promise 数组,然后使用 Promise.all,我知道很粗糙,但它应该可以工作。

const searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2']
const imageURLs = []
var promises = [];
 for(var Obj in searchPaths) 
{
    promises.push(new Promise(function(resolve, reject) {
      const path = Obj
      admin.database().ref(path).once('value').then(snapshot => 
      { 
      const URL = snapshot.val().fileURL;
      imageURLs.push(URL);
      console.log('ImageURL: ' + URL );

      //resolve the promise after pushing imageURL
      resolve();
      })
    }));
}

//when all of them are done:
Promise.all(promises)
.then(function(results) {
  //code when done...
})

关于javascript - 循环数据以提取 Firebase 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48964499/

相关文章:

javascript - firebase:获取ThenableReference的 key

java - 从 firebase 检索我的电话号码

javascript - Java/Firebase 脚本执行多次

javascript - JS 中的 flex 滚动和菜单栏错误

javascript - 少任务未找到错误

java - 将 dialogflow 依赖项添加到我的 android 应用程序后出现重复类错误

ios - Firebase + swift : Unable to delete rows in tableView

typescript - Firebase 消息传递 typescript : How import Message type?

javascript - React Native - 创建形状的 flex 边缘

javascript - 从 Firebase 数据库加载数据并使用 JavaScript 放置在 map 的标记上