0
votes

I'm new to both react and firebase. I'm trying to get a string of file names (just as a continuous string for right now) from a particular folder in the firebase storage bucket. My code is as follows:

getFilesList(){
    var toReturn="";
    toReturn+="Testing";
    var storage = firebase.app().storage(".....");
    var storageRef = storage.ref();
    var listRef = storageRef.child("/slides/1HdDPbTarLBxzllDlA3H/Lecture1/");
    listRef.listAll().then(function(result) {
    result.items.forEach(function(imageRef) {
    toReturn+=this.getImageString(imageRef);
  });
}).catch(function(error) {
  toReturn+="error1";
});

    return toReturn;
}
getImageString(imageRef) {
    var toReturn="T1";
  imageRef.getDownloadURL().then(function(url) {
    var toReturn=url.toString();
  }).catch(function(error) {
    toReturn+="error2";
  });
  return toReturn;
}

I'm not getting any errors, but the return string is blank (aside from the 'Testing' prefix). The folder has about 20 jpg files, but it seems as though it isn't seeing that they are there. I did some research online about it, but I'm still not sure why my code isn't working. Please help me to know why this isn't working?

Thank you,

Jared

1

1 Answers

0
votes

This isn't a problem with your framework, it's a problem with asynchronous code.

See, toReturn will eventually update with the results of that function call. The problem is that the caller of this function receives the array immediately, before any of the code in .then has a chance to touch it.

Even if the promise resolves instantly, the code above it will have already executed. Promises get put on a queue where the top item only executes after the current synchronous code has finished.

What getFilesList needs to do is return a Promise that the caller can then attach to in order to specify its own behaviour:

getFilesList(){
    var toReturn="";
    toReturn+="Testing";
    var storage = firebase.app().storage(".....");
    var storageRef = storage.ref();
    var listRef = storageRef.child("/slides/1HdDPbTarLBxzllDlA3H/Lecture1/");
    listRef.listAll().then(function(result) {
        result.items.forEach(function(imageRef) {
            toReturn+=this.getImageString(imageRef);
        });
        return toReturn;
     }).catch(function(error) {
         toReturn+="error1";
         return toReturn;
     });

And in the caller:

getFilesList.then(filesList => console.log(filesList))