gpt4 book ai didi

javascript - Vue 2 + Firebase - 上传到 Firebase 存储后执行功能

转载 作者:行者123 更新时间:2023-11-30 21:03:29 26 4
gpt4 key购买 nike

我想在 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()
})
}
}

最佳答案

根据docs :

put() and putString() both return an UploadTask which you can use as a promise, or use to manage and monitor the status of the upload.

所以你可以使用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()
})
}

关于javascript - Vue 2 + Firebase - 上传到 Firebase 存储后执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46875346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com