【问题标题】:Vue 2 + Firebase - Execute function after upload to Firebase StorageVue 2 + Firebase - 上传到 Firebase 存储后执行功能
【发布时间】:2018-04-03 04:11:12
【问题描述】:

我想在for循环完成并上传完成后执行代码this.createListing()。 如果我在 for 循环之后运行它,则不会考虑所有上传是否已完成。因此它不会从上传的文件中获取downloadURL

理想情况下,我希望在所有上传完成后运行该功能。 任何帮助表示赞赏。这是我的代码:

submitForm() {
    const user = firebase.auth().currentUser
    const listingPostKey = firebase.database().ref('listings/').push().key
    const listingRef = firebase.database().ref('listings/' + listingPostKey)

    for (let i = 0; i < this.uploadedImages.length; i++) {
        var storageRef = firebase.storage().ref('images/' + user.uid + '/' + this.imageName)
        var uploadTask = storageRef.put(this.uploadedImages[i])

        uploadTask.on('state_changed', (snapshot) => {
            var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
        }, error => {
            this.errors.push(error.message)
        }, () => {
           // Upload complete
           var downloadURL = uploadTask.snapshot.downloadURL
           this.images_url.push(downloadURL)
           this.createListing()
        })
    }
}

【问题讨论】:

    标签: javascript firebase vue.js firebase-storage


    【解决方案1】:

    根据docs

    put()putString() 都返回 UploadTask,您可以将其用作承诺,或用于管理和监控上传状态。

    所以您可以使用Promise.all 等待所有上传完成。

    这是我想出的代码:

    submitForm() {
        const user = firebase.auth().currentUser
        const listingPostKey = firebase.database().ref('listings/').push().key
        const listingRef = firebase.database().ref('listings/' + listingPostKey)
        const storageRef = firebase.storage().ref('images/' + user.uid + '/' + this.imageName)
    
        // map uploadedImages to array of uploadTasks (promises)
        const uploads = this.uploadedImages.map(uploadedImage => {
            const uploadTask = storageRef.put(uploadedImage)
    
            // you probably don't need this part
            // since 'progress' is not used anywhere
            uploadTask.on('state_changed', snapshot => {
                var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
            })
    
            return uploadTask.then(snapshot => {
                this.images_url.push(snapshot.downloadURL)
            })
        })
    
        // wait for all uploadTasks to be done
        Promise.all(uploads).then(() => {
            this.createListing()
        })
    }
    

    【讨论】:

    • 这绝对是一种魅力!谢谢你,杰克!不过,我仍然需要 for 循环的“i”,即索引。但这很容易添加到地图功能this.uploadedImages.map((uploadedImage, index) =&gt; { ... })
    猜你喜欢
    • 2018-12-24
    • 2018-12-06
    • 2020-03-05
    • 2020-09-28
    • 2021-04-21
    • 2021-10-28
    • 2018-01-24
    • 2021-04-27
    • 2020-11-22
    相关资源
    最近更新 更多