Firebase存储-等待所有上传任务完成后再执行功能 [英] Firebase Storage - Wait till all upload tasks are completed before executing function

查看:71
本文介绍了Firebase存储-等待所有上传任务完成后再执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将一个或多个文件上传到Firebase Storage.上传完成后,将在控制台中记录downloadURL.

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.

当所有文件都上传后,我想执行另一个功能,而不是forEach函数.完成所有上传任务后,如何打印控制台日志?

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');
}

推荐答案

UploadTask 对象的行为与承诺一样,因为它们具有然后()和catch()方法.因此,您可以将它们全部收集到一个数组中,并使用Promise.all()生成另一个承诺,当所有上载完成时该承诺将解决.

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');
});

这篇关于Firebase存储-等待所有上传任务完成后再执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆