简体   繁体   中英

Loop through data to pull array of firebase values

I have a an array of a number of N paths to retrieve data from a different location in firebase database.

searchPaths = ['locations/date1/imageID', 'locations/date2/imageID2', locations/date3/imageID3, ...]

now, I want to loop through each search path and pull a value from it to save an array of image URL's.

    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")
    }

So, my question is, how do I return a promise when we have now pulled the data we need from every ref? is there a Promise.all type? where does it go?

You can use the for-loop to create an array of promises, then use Promise.all , crude I know but it should work.

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...
})

The other answer here is going through too much trouble to collect promises. It's easier to just push the return value of once() into the promises array rather than creating a new promise each time.

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 );
    }
})

The then callback on the promise returned from Promise.all() will be an array of all the snapshots from the queries pushed into the promises array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM