admin管理员组文章数量:1390555
I'm using the following code to upload one or multiple files to Firebase Storage. When the upload is pleted 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 pleted?
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 pleted
console.log('all uploads plete');
}
I'm using the following code to upload one or multiple files to Firebase Storage. When the upload is pleted 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 pleted?
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 pleted
console.log('all uploads plete');
}
Share
Improve this question
asked Jul 17, 2018 at 3:25
ThoreThore
1,8682 gold badges31 silver badges65 bronze badges
1 Answer
Reset to default 8UploadTask 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 plete.
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 plete');
});
版权声明:本文标题:javascript - Firebase Storage - Wait till all upload tasks are completed before executing function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744698038a2620398.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论