1

In the code below, I'm trying to execute importPlacesToFirebase AFTER all current user images are removed with the removeUserImages function. I chose to solve this problem using the Firebase promises that are returned when executing delete or remove methods.

For some reason the importPlacesToFirebase function executes BEFORE all images are deleted.

// self.imagesRef is a database reference to the node where all user image metadata is stored. 
self.imagesRef.once('value').then(removeUserImages)
    .then(importPlacesToFirebase(jsonData));
function importPlacesToFirebase(jsonData) {
    console.log("start import");
    self.placesRef.set(jsonData.places, function handleError(err){
        if(err){
            console.log("error: " + err);
        } else {
            console.log("imported");
            //reload the current document
            //location.reload();
        }
    });
}

// Remove al images related to a user
function removeUserImages(snap) {
    var removals = [];
    snap.forEach(function(childSnapshot){
        var promise = removePlaceImages(childSnapshot);
        removals.push(promise);
    });
    return Promise.all(removals);
}

// Remove all images related to a place
function removePlaceImages(snap) {
    var removals = [];
    snap.forEach(function(childSnapshot){
        var promise = removeSingleImage(childSnapshot);
        removals.push(promise);
    });
    return Promise.all(removals);
}

// Remove the image metadata and remove the actual image from the storage
function removeSingleImage(snap){
    var url = snap.val().url;
    return Promise.all([snap.ref.remove(), removeImageWithUrl(url)]);
}

// Remove actual image from storage
function removeImageWithUrl(url) {
    // Request the firebase storage reference of the image
    var httpRef = firebase.storage().refFromURL(url);
    return httpRef.delete();
}
sjbuysse
  • 3,872
  • 7
  • 25
  • 37
  • 2
    `then(importPlacesToFirebase(jsonData));` because you're calling the function, rather than passing a function as `.then` requires - try `.then(() => importPlacesToFirebase(jsonData));` – Jaromanda X Apr 09 '17 at 22:35
  • Thanks for pointing out the bug in this code guys! Much appreciated – sjbuysse Apr 09 '17 at 22:49

0 Answers0