如何等待getDownloadUrl异步函数执行完毕后再推送数据至数据库?
问题解决:确保所有图片URL获取完成后再执行数据库操作
原代码的核心问题是getDownloadUrl方法里的forEach循环搭配异步回调时,forEach不会等待每个异步操作完成,导致方法提前返回,此时newCardData.images数组还没收集完所有URL,后续的数据库推送就已执行。
修复后的代码
async getDownloadUrl(newCardData) { const cardImagesRef = await this.$fire.storage .ref('/albums_cards/') .child(uuidV1()) // 用map生成Promise数组,通过Promise.all等待所有异步操作完成 await Promise.all(this.newCard.cardImages.map(async (image) => { const imageRef = cardImagesRef.child(uuidV4()) await imageRef.put(image) const url = await imageRef.getDownloadURL() newCardData.images.push(url) })) }, async postNewCard() { this.newCard.loading = true const newCardData = { title: this.newCard.cardTitle, description: this.newCard.cardSnippet, images: [], } await this.getDownloadUrl(newCardData) await this.$fire.database.ref('albums/cards').push(newCardData) this.newCard.loading = false this.newCard.cardTitle = null this.newCard.cardSnippet = null this.newCard.cardImages = [] this.newCard.cardImageUrls = [] },
关键修改说明
- 替换
forEach为map:map会返回每个异步操作生成的Promise对象,而forEach不会处理回调的返回值,无法追踪异步任务状态。 - 新增
Promise.all():等待所有图片的上传、URL获取操作全部完成后,getDownloadUrl方法才会结束,确保newCardData.images数组已收集到所有图片的下载URL。
内容的提问来源于stack exchange,提问作者Rustam Ravshanovich
相关产品推荐
相关产品推荐

