回调函数在所有Promise解析之前执行。

时间:2017-04-09 22:28:02

标签: javascript asynchronous firebase promise

在下面的代码中,我试图在使用importPlacesToFirebase功能删除所有当前用户图像后执行removeUserImages。我选择使用在执行deleteremove方法时返回的Firebase承诺来解决此问题。

由于某种原因,importPlacesToFirebase函数在删除所有图像之前执行。

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

0 个答案:

没有答案