循环遍历数据以获取firebase值的数组

时间:2018-02-24 15:34:39

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

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

searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2', locations/date3/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")
    }

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

2 个答案:

答案 0 :(得分:1)

你可以使用for循环创建一个promises数组,然后使用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...
})

答案 1 :(得分:1)

这里的另一个答案是收集承诺会遇到太多麻烦。将once()的返回值推送到promises数组中更容易,而不是每次都创建一个新的promise。

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

searchPaths.forEach(path => {
    promises.push(admin.database().ref(path).once('value'))
})

Promise.all(promises).then(results => {
    results.forEach(snapshot => {
        const URL = snapshot.val().fileURL;
        imageURLs.push(URL);
        console.log('ImageURL: ' + URL );
    }
})

从Promise.all()返回的promise的then回调将是推送到promises数组中的查询的所有快照的数组。