如何获取Firebase Storage可下载链接数组并正确存入MongoDB?
问题原因与解决方案
核心问题
你的getLinks函数是同步返回数组,但内部的uploadBytes和getDownloadURL都是异步Promise操作——函数执行时会立刻返回空数组,等异步操作完成并往数组push链接时,createAdd已经把空数组传给createPost并存入MongoDB了,所以photos字段始终为空。
修复代码
1. 重构getLinks为异步函数,用Promise.all等待所有链接获取完成
const getLinks = async (values) => { // 为每张图片生成上传+获取链接的Promise const uploadPromises = values.adImgs.map(async (image: any) => { const imgPath = `ad_images/${image.name + v4()}`; const imageRef = ref(storage, imgPath); const snapshot = await uploadBytes(imageRef, image); return getDownloadURL(snapshot.ref); }); // 等待所有异步操作完成,返回完整的链接数组 return Promise.all(uploadPromises); }
2. 修改createAdd函数,等待getLinks返回结果后再创建文档
const createAdd = async (values) => { // 等待所有图片链接获取完成 const photos = await getLinks(values); const newObj: any = { title: values.title, photos: photos } await createPost(newObj); }
关键说明
Promise.all会等待传入的所有Promise都完成后,返回一个包含所有结果的数组,确保你拿到的是完整的图片链接列表。- 必须用
await调用getLinks,否则依然会拿到未完成的Promise对象,而非最终的链接数组。
内容的提问来源于stack exchange,提问作者asela daskon
相关产品推荐
相关产品推荐

