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

后端 未结 1 338
一个人的身影
一个人的身影 2020-12-21 12:38

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 lik

相关标签:
1条回答
  • 2020-12-21 13:03

    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');
    });
    
    0 讨论(0)
提交回复
热议问题