Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - How to upload images to firebase storage and wait for URLs to return before continuing

I'm trying to create a "Create Post" form where the user can input text, as well as input images.

uploadImages() {
    const files = document.querySelector('#imagesInput').files;
    files.forEach(image => {
        console.log("uploading", image.name)
        const name = (+new Date()) + '-' + image.name;
        const task = fb.storage.child(name).put(image, {contentType: image.type});
        task.then(snapshot => {
            snapshot.ref.getDownloadURL().then(url => {
                console.log(url);
            })
        })
    });
}

The image upload process needs to happen first, and I need to return all the URLs (as an array) before the post is created in the database.

imageURLs = this.uploadImages(); // <-- Wait for this to complete and return the image URIs
this.createPost("Hello, world!", imageURLs) // <-- then do this
question from:https://stackoverflow.com/questions/65868649/how-to-upload-images-to-firebase-storage-and-wait-for-urls-to-return-before-cont

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you call the asynchronous getDownloadURL() method a variable number of times (i.e. unknown at the time of coding), you need to use Promise.all() as follows:

uploadImages() {
    const files = document.querySelector('#imagesInput').files;

    const promises = [];
    files.forEach(image => {
        console.log("uploading", image.name)
        const name = (+new Date()) + '-' + image.name;
        const task = fb.storage.child(name).put(image, { contentType: image.type });
        promises.push(task);
    });

    return Promise.all(promises)
        .then(snapshotsArray => {
            // snapshotsArray is an array with a variable number of elements
            // You again need to use Promise.all
            const promises = [];
            snapshotsArray.forEach(snapshot => {
                promises.push(snapshot.ref.getDownloadURL());
            })
            return Promise.all(promises);
        });
}

The uploadImages() function is asynchronous and returns a Promise (since Promise.all() and then() return Promises): you therefore need to call it by using then(), as follows:

this.uploadImages()
.then(imageURLs => {
   this.createPost("Hello, world!", imageURLs) 
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...