Firebase Storage - Wait till all upload tasks are completed before executing function

岁酱吖の 提交于 2020-01-21 13:27:13

问题


I'm using the following code to upload one or multiple files to Firebase Storage. When the upload is completed the downloadURL is logged in the console.

I would like to execute another function when all the files are uploaded, outside the forEach function. How can I print the console log when all the uploads tasks are completed?

onSubmit = e => {
    e.preventDefault();
    const { files } = this.state;

    files.forEach(file => {
        const uploadTask = Storage.ref(`files/${file.name}`).put(file);

        uploadTask.on('state_changed', snapshot => {
            const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log(progress);
        }, error => { console.log(error) }, () => {
            uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
                console.log(downloadURL);
            });
        });
    });

    //Wait till all uploads are completed
    console.log('all uploads complete');
}

回答1:


UploadTask objects behave just like promises, as they have then() and catch() methods. So, you can collect them all into an array and use Promise.all() to generate a another promise that resolves when all the uploads are complete.

const promises = [];
files.forEach(file => {
    const uploadTask = Storage.ref(`files/${file.name}`).put(file);
    promises.push(uploadTask);

    uploadTask.on('state_changed', snapshot => {
        const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
        console.log(progress);
    }, error => { console.log(error) }, () => {
        uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
            console.log(downloadURL);
        });
    });
});

Promise.all(promises).then(tasks => {
    console.log('all uploads complete');
});


来源:https://stackoverflow.com/questions/51372789/firebase-storage-wait-till-all-upload-tasks-are-completed-before-executing-fun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!